Full answer
Setup for the example:
sql
CREATE TABLE sales (region text, amount int);
INSERT INTO sales VALUES ('north', 100), ('south', 50), ('north', 70);
CREATE MATERIALIZED VIEW region_totals AS SELECT region, sum(amount) AS total FROM sales GROUP BY region;sql
REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals;PostgreSQL returns:
text
ERROR: cannot refresh materialized view "ib_0046.region_totals" concurrentlysql
CREATE UNIQUE INDEX region_totals_region ON region_totals (region); INSERT INTO sales VALUES ('east', 30), ('south', 25); REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals; SELECT region, total FROM region_totals ORDER BY region;Result on PostgreSQL 17:
text
region | total
--------+-------
east | 30
north | 170
south | 75
(3 rows)sql
CREATE MATERIALIZED VIEW empty_mv AS SELECT * FROM sales WITH NO DATA; SELECT ispopulated FROM pg_matviews WHERE matviewname = 'empty_mv';Result:
text
ispopulated
-------------
f
(1 row)Without a unique index, the concurrent refresh fails with 'cannot refresh materialized view ... concurrently', and the error's hint asks for a unique index. After adding a unique index on region, new sales are merged in while readers could keep querying: east appears and south rises to 75. A view created WITH NO DATA is not populated, cannot be queried until refreshed, and its first refresh must be a plain one. Schedule refreshes with cron or pg_cron, and monitor their duration, because a concurrent refresh scans the full query each time.
sql
CREATE TABLE sales (region text, amount int);
INSERT INTO sales VALUES ('north', 100), ('south', 50), ('north', 70);
CREATE MATERIALIZED VIEW region_totals AS SELECT region, sum(amount) AS total FROM sales GROUP BY region;
REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals;
CREATE UNIQUE INDEX region_totals_region ON region_totals (region); INSERT INTO sales VALUES ('east', 30), ('south', 25); REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals; SELECT region, total FROM region_totals ORDER BY region;
CREATE MATERIALIZED VIEW empty_mv AS SELECT * FROM sales WITH NO DATA; SELECT ispopulated FROM pg_matviews WHERE matviewname = 'empty_mv';Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Plain REFRESH blocks readers
- CONCURRENTLY needs a unique index
- Concurrent refresh is slower
- WITH NO DATA views need a first plain refresh
- Schedule and monitor refreshes
Common mistakes
- Refreshing large views at peak without CONCURRENTLY
- Unique indexes that do not cover all rows
Follow-ups
- How would you refresh incrementally instead?
- When should a summary table replace a materialized view?
Tips
- Name the unique index requirement