PostgreSQL - get materialized view column metadata

Queries for this kind of question can easily be retrieve when running psql with the -E ("echo hidden queries") option.

The following query should do what you want:

SELECT a.attname,
       pg_catalog.format_type(a.atttypid, a.atttypmod),
       a.attnotnull
FROM pg_attribute a
  JOIN pg_class t on a.attrelid = t.oid
  JOIN pg_namespace s on t.relnamespace = s.oid
WHERE a.attnum > 0 
  AND NOT a.attisdropped
  AND t.relname = 'mv_name' --<< replace with the name of the MV 
  AND s.nspname = 'public' --<< change to the schema your MV is in 
ORDER BY a.attnum;

I spent some time on this today - I was building a metadata view that showed all schemas, tables, and columns in a database.

I had to do a bit of digging to make the metadata for my materialized views available in the same way as tables or regular views (since materialized views are not included in information_schema), but here's where I ended up:

SELECT pg_namespace.nspname AS table_schema
    , pg_class.relname AS table_name
    , 'materialized view'::TEXT AS table_type
    , pg_attribute.attname AS column_name
    , pg_attribute.attnum AS ordinal_position
FROM pg_catalog.pg_class
    INNER JOIN pg_catalog.pg_namespace
        ON pg_class.relnamespace = pg_namespace.oid
    INNER JOIN pg_catalog.pg_attribute
        ON pg_class.oid = pg_attribute.attrelid
-- Keeps only materialized views, and non-db/catalog/index columns 
WHERE pg_class.relkind = 'm'
    AND pg_attribute.attnum >= 1
ORDER BY table_schema
    , table_name
    , column_name

Tags:

Postgresql