Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 13 / Topic 2 of 8

Materialized views

When the saved query is expensive and the answer may be minutes stale, store the result: a materialized view computes once and serves from disk:

CREATE MATERIALIZED VIEW daily_sales AS
SELECT o.order_date,
       count(DISTINCT o.order_id)       AS orders,
       sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY o.order_date;
SELECT * FROM daily_sales ORDER BY order_date LIMIT 3;
SELECT 6
 order_date | orders | revenue 
------------+--------+---------
 2025-01-10 |      1 | 1270.00
 2025-01-25 |      1 |  799.00
 2025-02-14 |      1 |  135.00
(3 rows)

Fast reads, one honest catch: it goes stale — new orders don't appear until you REFRESH MATERIALIZED VIEW daily_sales; (typically from a scheduled job). Plain REFRESH locks reads while it rebuilds; REFRESH ... CONCURRENTLY keeps readers flowing — but demands a unique index so it can diff old against new:

REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;
ERROR:  cannot refresh materialized view "public.daily_sales" concurrently
HINT:  Create a unique index with no WHERE clause on one or more columns of the materialized view.

Postgres refuses and tells you why. Give it the index and it's happy:

CREATE UNIQUE INDEX daily_sales_pk ON daily_sales (order_date);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;
CREATE INDEX
REFRESH MATERIALIZED VIEW

View vs matview is Part 9's trade again: live-but-recomputed versus fast-but-stale-with-a-refresh-obligation. Dashboards and reports love matviews; anything needing this-second truth doesn't.

🧪 Quick quiz — answer from memory, then check.

  1. What does REFRESH ... CONCURRENTLY require, and what does it buy?
  2. When is a matview the wrong tool?
Show the answers
  1. A unique index on the matview; readers keep working during the refresh.
  2. When readers need current truth — a matview is as fresh as its last refresh, by design.

Done here? The practice set for Part 13 — 6 exercises with solutions — is on the part page.

Search the guide