Video in progress

What is a materialized view, how does it differ from a regular VIEW, and how do you refresh it?

A regular VIEW is a saved query that runs again on every access. A materialized view stores the result on disk like a table, so it reads fast, but it goes stale and must be refreshed with REFRESH MATERIALIZED VIEW.

📖 Answer

Say you have a heavy dashboard query: monthly statistics over several million orders. Computing it every time a page opens is expensive.

CREATE MATERIALIZED VIEW monthly_sales AS
SELECT date_trunc('month', created_at) AS month,
       shop_id,
       sum(total) AS revenue,
       count(*)   AS orders
FROM orders
GROUP BY 1, 2;

CREATE UNIQUE INDEX ON monthly_sales (month, shop_id);

Now SELECT * FROM monthly_sales runs in milliseconds. You can put a regular index on it as well.

There are two ways to refresh:

REFRESH MATERIALIZED VIEW monthly_sales;               -- reads are blocked during the refresh
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_sales;  -- doesn't block reads

CONCURRENTLY requires a unique index on the view, and it's slower because it compares the old and new results.

PostgreSQL doesn't refresh a materialized view automatically or partially: every refresh re-runs the whole query. So I refresh it with a @Scheduled job in Spring or with pg_cron, say every 10 minutes, and the UI carries an agreement that "data may be up to 10 minutes old".