Sub topic 9
Checking state with the pg_matviews view
A materialized view stores query results, so it can fall out of step with its base tables. It can also be missing its data, missing an index, or grow larger than you expect. PostgreSQL has no dedicated "status" command for these cases. You check state by reading the system catalog view pg_matviews and a few related catalogs. This chapter assumes you can already create, index, and refresh a materialized view. It uses the orders table and the sales_daily and customer_totals views from earlier chapters.
What pg_matviews exposes
pg_matviews is a system view with one row for each materialized view in the database. It has seven columns.
| Column | Meaning |
|---|---|
| `schemaname` | Schema that contains the materialized view |
| `matviewname` | Name of the materialized view |
| `matviewowner` | Role that owns it |
| `tablespace` | Tablespace name, or null if the database default is used |
| `hasindexes` | True if the view has, or recently had, any indexes |
| `ispopulated` | True if the view currently holds data |
| `definition` | The query text that defines the view |
A basic overview of every materialized view looks like this:
SELECT schemaname, matviewname, matviewowner, hasindexes, ispopulated
FROM pg_matviews
ORDER BY schemaname, matviewname;Two points about this view often surprise people:
pg_matviewslists every materialized view in the database, including those you have no privilege to read. Seeing a view in the list does not mean you can query it.- There is no column for the time of the last refresh. PostgreSQL does not record that time. The section on tracking freshness below covers ways to work around this.
Reading ispopulated
ispopulated tells you whether the view can be queried at all. A view is populated after a normal CREATE MATERIALIZED VIEW or after any successful REFRESH. It is unpopulated after CREATE MATERIALIZED VIEW ... WITH NO DATA. It also becomes unpopulated again if you run REFRESH MATERIALIZED VIEW ... WITH NO DATA.
CREATE MATERIALIZED VIEW customer_totals AS
SELECT customer_id, sum(total) AS lifetime_value
FROM orders
GROUP BY customer_id
WITH NO DATA;
SELECT matviewname, ispopulated
FROM pg_matviews
WHERE matviewname = 'customer_totals';The result shows ispopulated = f. Querying the view at this point fails:
ERROR: materialized view "customer_totals" has not been populated
HINT: Use the REFRESH MATERIALIZED VIEW command.After the first refresh, the flag becomes true:
REFRESH MATERIALIZED VIEW customer_totals;
SELECT matviewname, ispopulated
FROM pg_matviews
WHERE matviewname = 'customer_totals';The flag only says whether data is present. A populated view can still be days out of date, so ispopulated = t says nothing about freshness.
A useful monitoring query lists every view that is not ready to be read:
SELECT format('%I.%I', schemaname, matviewname) AS unpopulated_view
FROM pg_matviews
WHERE NOT ispopulated;format() with %I quotes identifiers correctly, so names with capital letters or spaces still work when you paste them into later commands.
Reading hasindexes
hasindexes is a quick check for a view with no indexes at all. If a large view that you query by key shows hasindexes = f, every lookup is a sequential scan. The flag is only a hint. It cannot tell you whether the existing indexes suit your queries, and it can stay true for a short while after the last index is dropped. To see the indexes themselves, query pg_indexes, which covers materialized views as well as tables:
SELECT indexname, indexdef
FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = 'sales_daily';The column is called tablename even when the relation is a materialized view.
Checking whether CONCURRENTLY will work
REFRESH MATERIALIZED VIEW CONCURRENTLY needs a unique index that meets three conditions. The index must cover plain columns only, with no expressions. It must have no WHERE clause. It must be valid. The view must also already be populated. You can test the index conditions for every view in one query:
SELECT m.schemaname,
m.matviewname,
m.ispopulated,
EXISTS (
SELECT 1
FROM pg_index i
WHERE i.indrelid = format('%I.%I', m.schemaname, m.matviewname)::regclass
AND i.indisunique
AND i.indisvalid
AND i.indpred IS NULL
AND i.indexprs IS NULL
) AS has_concurrent_ready_index
FROM pg_matviews m
ORDER BY m.schemaname, m.matviewname;This query reads pg_index, the catalog that stores index properties. The ::regclass cast converts a quoted schema-qualified name into the relation's object ID, which is what indrelid stores.
Run this query before you put a CONCURRENTLY refresh into a scheduled job. If the check returns false for a view, the scheduled command will fail on every run.
Measuring size
Materialized views occupy disk space like tables do. Because pg_matviews has no size column, use the size functions together with the same format(...)::regclass pattern:
SELECT matviewname,
pg_size_pretty(
pg_relation_size(format('%I.%I', schemaname, matviewname)::regclass)
) AS data_size,
pg_size_pretty(
pg_total_relation_size(format('%I.%I', schemaname, matviewname)::regclass)
) AS total_size
FROM pg_matviews
ORDER BY pg_total_relation_size(format('%I.%I', schemaname, matviewname)::regclass) DESC;pg_relation_size counts the main data only. pg_total_relation_size adds indexes and TOAST storage, which is where PostgreSQL moves oversized column values. A large gap between the two numbers means the indexes cost a lot of space.
An unpopulated view takes almost no space, which makes size a second way to spot one.
A non-concurrent refresh builds a fresh copy of the data and swaps it in. During that moment, the old and new copies both exist on disk, so you need free space of about the view's size. A concurrent refresh builds a temporary table and applies a diff, so it also needs temporary space plus the cost of inserting and deleting rows. Size figures help you plan disk headroom.
Row counts and statistics
Materialized views appear in the statistics views that cover tables. pg_stat_user_tables shows an estimated live row count and the last time autovacuum or analyze touched the view:
SELECT relname,
n_live_tup,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
WHERE relname IN ('sales_daily', 'customer_totals');n_live_tup is an estimate maintained by the statistics collector, so use count(*) when you need an exact figure. Do not read last_autoanalyze as a refresh time. Autovacuum decides when to analyze, and a refresh does not necessarily trigger it. After a large refresh, run ANALYZE sales_daily; yourself if the planner picks poor plans for queries against the view.
Tracking freshness yourself
Since PostgreSQL does not record refresh times, you have to create the record. Two approaches work well.
The first is to put a timestamp inside the view. Every refresh then replaces the stamp:
CREATE MATERIALIZED VIEW sales_daily_stamped AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue,
now() AS refreshed_at
FROM orders
GROUP BY order_date;
SELECT max(refreshed_at) AS last_refresh
FROM sales_daily_stamped;now() returns the start time of the refreshing transaction, so every row carries the same value. This approach costs one extra column and lets a dashboard display "data as of" with no separate bookkeeping. It requires you to define the view with the column from the start. Adding the column to an existing view means dropping and recreating it, because PostgreSQL cannot change a materialized view's query in place.
The second approach is to read the scheduler's own history. If you use pg_cron, it records every run in cron.job_run_details:
SELECT j.jobname,
d.status,
d.start_time,
d.end_time,
d.return_message
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE j.jobname = 'refresh-sales-daily'
ORDER BY d.start_time DESC
LIMIT 5;This shows when the last attempt ran and whether it succeeded, including the error text of failed runs. It tells you about the job, not about the data. If someone also refreshes the view by hand, the history will not show that.
Reading the stored definition
The definition column holds the query PostgreSQL stored, reformatted from your original text:
SELECT definition
FROM pg_matviews
WHERE schemaname = 'public'
AND matviewname = 'sales_daily';Expect different whitespace, qualified column names, and explicit casts compared with what you typed. This is the way to recover a view's query when the original script is lost, for example before you rebuild a view with changes. In psql you can see the same information with \d+ sales_daily, and \dm lists all materialized views.
A combined health check
The pieces above fit into one report. It uses a LEFT JOIN to pg_stat_user_tables so unpopulated views still appear:
SELECT m.schemaname,
m.matviewname,
m.ispopulated,
m.hasindexes,
pg_size_pretty(
pg_total_relation_size(format('%I.%I', m.schemaname, m.matviewname)::regclass)
) AS total_size,
s.n_live_tup AS approx_rows
FROM pg_matviews m
LEFT JOIN pg_stat_user_tables s
ON s.schemaname = m.schemaname
AND s.relname = m.matviewname
ORDER BY m.schemaname, m.matviewname;Common mistakes
- Treating
ispopulatedas a freshness flag. It only reports whether data exists. - Looking for a last-refresh column. None exists. Add a timestamp column or log the refresh jobs.
- Filtering
pg_matviewsby name alone. The same name can exist in several schemas. Always includeschemaname. - Building relation names by string concatenation. Use
format('%I.%I', ...)so quoting is handled for you. - Assuming visibility means access. The view lists all materialized views, but you still need
SELECTprivilege to read one.
Exercise
You schedule REFRESH MATERIALIZED VIEW CONCURRENTLY customer_totals and every run fails. pg_matviews shows ispopulated = t and hasindexes = t for the view. Name two checks you would run to find the cause and what you would look for.
Show answer
First, query pg_index for the view (indrelid = 'public.customer_totals'::regclass) and look for an index that is unique, valid (indisvalid), has no predicate (indpred IS NULL), and has no expression columns (indexprs IS NULL). hasindexes = t only says some index exists. It could be a non-unique index, a partial unique index, or one built on an expression, and none of those satisfy CONCURRENTLY. Second, read the failure text, for example from cron.job_run_details.return_message if you use pgcron, to confirm the error is the missing unique index requirement. The fix is to create a plain unique index on columns that identify each row, such as `CREATE UNIQUE INDEX ON customertotals (customer_id);`.
Exercise
Write a query that lists the schema-qualified name and total size (including indexes) of every unpopulated materialized view. Why is the size usually tiny?
Show answer
SELECT format('%I.%I', schemaname, matviewname) AS matview, pgsizepretty(pgtotalrelationsize(format('%I.%I', schemaname, matviewname)::regclass)) AS totalsize FROM pg_matviews WHERE NOT ispopulated; The size is tiny because a view created WITH NO DATA stores no rows. Only the empty relation, and any indexes created on it, take space.