I am wondering if it is possible to extract the column name, data type, and one sample value from a database table with a single PostgreSQL query. I'm aiming to do this for all columns of one table.
Feels like a variable is needed for the column name so you can use it when querying the table for the sample value but Postgres doesn't support this in plain SQL statement (How to declare a variable in a PostgreSQL query).
I can achieve this through hard-coding a single value but any suggestions on whether this is possible to do for each column of the table (join each one using its name in a select statement to obtain the single sample value)?
column | data_type | sample_val -------------------------------- foo_col1 | text | NULL foo_col2 | text | 'foo_val2' foo_col3 | text | NULL
select column_name as column, data_type, sample_val
from information_schema.columns t1
join pg_class t2 on (t1.table_name = t2.relname)
left outer join pg_description t3 on (t2.oid = t3.objoid and t3.objsubid = t1.ordinal_position)
left outer join (select CAST('foo_col2' AS text) as foo_col2, foo_col2 as sample_val from foo_schema.foo_table limit 1) n2
on (n2.foo_col2 = column_name)
where table_schema = 'foo_schema'
and table_name = 'foo_table'
order by ordinal_position