Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - get materialized view column metadata

Tags:

postgresql

This is similar to Column data types for materialized views? but I need more data (not just data type). I would like to have the same kind of query that I do for tables/views but for materialized views.

SELECT column_name, data_type, character_maximum_length,
      character_octet_length, numeric_precision, numeric_precision_radix,
     numeric_scale, datetime_precision, interval_type, interval_precision
     FROM information_schema.columns
    WHERE table_schema = '{}'
    AND table_name   = '{}'
    order by ordinal_position

Does anyone have something like this? Column names in pg_attribute are very cryptic.

like image 827
Andrey Vykhodtsev Avatar asked Aug 27 '16 08:08

Andrey Vykhodtsev


People also ask

Can you query a materialized view?

You can use a materialized view in any SQL query by referencing the materialized view name as the data source, like a table or standard view. When a query accesses a materialized view, it sees only the data that is stored in the materialized view as of its most recent refresh.

Can you index a materialized view Postgres?

Because a materialized view actually is a table, we can create indexes.


1 Answers

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;
like image 166
a_horse_with_no_name Avatar answered Oct 02 '22 14:10

a_horse_with_no_name