List materialized views and refresh times
Materialized views serve stale data by design, so the two things you want to know are which ones exist and when each was last refreshed. One of those the catalog answers.
The task
A dashboard fed by a materialized view shows numbers nobody trusts, so the first step is seeing which matviews exist, how large they are and whether they are populated.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT schemaname, matviewname, matviewowner,
ispopulated,
pg_size_pretty(pg_total_relation_size(
format('%I.%I', schemaname, matviewname)::regclass)) AS total_size
FROM pg_matviews
ORDER BY matviewname;
How it works
pg_matviews lists every materialized view with its owner and ispopulated, which is false only for a view created or refreshed WITH NO DATA; selecting from such a view raises an error. A failed REFRESH rolls back and leaves the previous contents in place. PostgreSQL records no last-refresh time, so stamp a log table from the job that runs REFRESH, in the same transaction, as the first variant does.
Variations
PostgreSQL: refresh with a freshness log
PostgreSQLCREATE TABLE IF NOT EXISTS matview_refresh_log (
matview text PRIMARY KEY,
refreshed_at timestamptz NOT NULL
);
BEGIN;
REFRESH MATERIALIZED VIEW CONCURRENTLY public.daily_sales;
INSERT INTO matview_refresh_log (matview, refreshed_at)
VALUES ('public.daily_sales', now())
ON CONFLICT (matview) DO UPDATE
SET refreshed_at = excluded.refreshed_at;
COMMIT;
SQL Server: indexed views
SQL Server-- SQL Server's materialized views are indexed views; every
-- write to a base table updates them, so there is nothing
-- to refresh
SELECT s.name AS schema_name, v.name AS view_name,
i.name AS clustered_index
FROM sys.views v
JOIN sys.schemas s ON s.schema_id = v.schema_id
JOIN sys.indexes i ON i.object_id = v.object_id AND i.index_id = 1;
Questions that come up
Why is REFRESH MATERIALIZED VIEW CONCURRENTLY failing?
CONCURRENTLY needs at least one unique index on the materialized view that uses only column names (no expressions or WHERE clause), and the view must already be populated. Unlike CREATE INDEX CONCURRENTLY it can run inside a transaction block. Without such an index you are left with the plain REFRESH, which holds an ACCESS EXCLUSIVE lock so readers wait until it finishes.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.