pg_matviews Lists Materialized Views
Inspect pg_matviews to see every materialized view, its owner, and refresh state, then compare with pg_views for plain views.
Code
-- pg_matviews:物化视图目录,包含定义文本与是否已填充数据
-- 前置表结构(orders 在本文件内自建,脚本可原样执行)
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
region text NOT NULL,
contact_email text,
placed_at timestamptz NOT NULL DEFAULT now()
);
CREATE MATERIALIZED VIEW mv_daily_totals AS
SELECT region, count(*) AS order_count
FROM orders
GROUP BY region
WITH NO DATA; -- 建成时未填充,ispopulated = false
SELECT matviewname, ispopulated, hasindexes
FROM pg_matviews
WHERE schemaname = 'public'
ORDER BY matviewname;
-- pg_views:普通视图在同一目录族里单独列出
CREATE VIEW v_recent_orders AS
SELECT id, contact_email FROM orders WHERE placed_at > now() - interval '7 days';
SELECT viewname, definition IS NOT NULL AS has_definition
FROM pg_views
WHERE schemaname = 'public';
-- 未填充的物化视图必须先 REFRESH 才能查询,否则报错
REFRESH MATERIALIZED VIEW mv_daily_totals;
SELECT * FROM mv_daily_totals ORDER BY region;How it works
The file runs SELECT / CREATE statements, touching orders, pg_matviews, pg_views and mv_daily_totals.
What the statements actually assemble: a WHERE clause constraining which rows the statement operates on; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
Point it at the orders table.
Key statements
CREATE MATERIALIZED VIEW mv_daily_totals AS
SELECT region, count(*) AS order_count
FROM orders
GROUP BY region
WITH NO DATA; -- 建成时未填充,ispopulated = false
CREATE VIEW v_recent_orders AS
SELECT id, contact_email FROM orders WHERE placed_at > now() - interval '7 days';
SELECT matviewname, ispopulated, hasindexes
FROM pg_matviews
WHERE schemaname = 'public'
ORDER BY matviewname;
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- The references are `orders`, `pg_matviews`, `pg_views`, `mv_daily_totals`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.