Question

I have a table users with columns user_id, user_name and user_phone for example.

If I do:

select hstore(u) from users u

the result is:

"user_id" => "1", "user_name" => "McEnroe", "user_phone" => "xxx"

If I do:

select hstore(u) from (select user_id, user_name, user_phone from users) u

the result is:

"f1" => "1", "f2" => "McEnroe", "f3" => "xxx"

I lose the name of the columns.
How can I use the 2nd example and having the correct column name?

Was it helpful?

Solution

This was a shortcoming that was fixed with Postgres 9.2.
I quote the release notes for 9.2 here:

E.5.3.3. Queries

(...)

  • Retain column names at run time for row expressions (Andrew Dunstan, Tom Lane)

    This change allows better results when a row value is converted to hstore or json type: the fields of the resulting value will now have the expected names.

Also, don't use user as table name, even if it's just a demo. It is a reserved word in every SQL standard and in Postgres and cannot be used as table name without double-quoting. I took the liberty to fix the test case in the Q.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top