Built on the answer by @Chris:
SELECT a.attnum
,a.attname AS name
,format_type(a.atttypid, a.atttypmod) AS typ
,a.attnotnull AS notnull
,coalesce(p.indisprimary, FALSE) AS primary_key
,f.adsrc AS default_val
,d.description AS col_comment
FROM pg_attribute a
LEFT JOIN pg_index p ON p.indrelid = a.attrelid AND a.attnum = ANY(p.indkey)
LEFT JOIN pg_description d ON d.objoid = a.attrelid AND d.objsubid = a.attnum
LEFT JOIN pg_attrdef f ON f.adrelid = a.attrelid AND f.adnum = a.attnum
WHERE a.attnum > 0
AND NOT a.attisdropped
AND a.attrelid = 'schema.tbl'::regclass -- table may be schema-qualified
ORDER BY a.attnum;
But:
Table names are not unique in a database and hence also not in the system catalog. You may have to schema-qualify the name.
Use a.attrelid = 'tbl'::regclass
as condition. This way you can pass myschema.mytbl
as name and disambiguate. Then there is no need to join to pg_class
at all in this case.
Also, visibility is checked automatically for regclass
and there is no need for pg_table_is_visible()
.
A primary key can span multiple columns. I take care of this by joining to pg_index
on a.attnum = ANY(p.indkey)
.
indkey
is of type int2vecor
, which is a special case of int2[]
, only used in the catalogs.
I find psql -E
helpful for this class of problems.
Compatibility
A specialized query like this might break after a major version update. Postgres does not guarantee that catalog tables remain stable. It is extremely unlikely that basic elements change, but the more complex and specialized your query gets, the bigger the chance. You could use the information schema instead, which is standardized, but also comparatively slow.