sql - Select column name and value from table -


if have following table in postgresql database:

col1    col2    col3                  1        b       b       2        

is there way column name each value without explicitly specifying column names? i.e. have result set like:

col1    col1    b col2    col2    b col3    1 col3    2 

of course, write pl/pgsql function , query catalog table pg_attribute yourself. it's easier 1 of following:

json

the function row_to_json() provides functionality goes half way. introduced postgres 9.2:

select row_to_json(t, true) tbl t; 

you don't have mention column names @ all, function derives them table type.

->sqlfiddle demo.

but you'll need json_each_text() postgres 9.3 go way:

select json_each_text(row_to_json(t)) tbl t; 

to sort order display:

select (json_each_text(row_to_json(t))).*   tbl t order  1, 2; 

(it's unclear how want sort exactly.)
untested. sqlfiddle not provide postgres 9.3, yet.

hstore

however, can same additional module hstore. available since 8.4. install once with:

create extension hstore; 

details:
key value pair in postgresql

query:

select (each(hstore(t))).*   tbl t order  1,2; 

that's all.
again, no sqlfiddle, since 1 can't install additional modules there.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -