Sub topic 3
Refreshing Data with `REFRESH MATERIALIZED VIEW`
This chapter assumes that you know SELECT, GROUP BY, aggregate functions, tables, plain views, and basic indexes. You also need access to a PostgreSQL database where you can create and modify objects.
A materialized view stores the result of its defining query. PostgreSQL does not automatically recalculate that result when the base tables change. The stored rows can therefore become stale. REFRESH MATERIALIZED VIEW runs the defining query again and replaces the materialized view's contents.
Refreshing the stored result
Suppose the database contains an orders table and a materialized view that summarizes daily sales:
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;The first CREATE MATERIALIZED VIEW command executes the query and stores its result. Later, new orders change orders, but they do not change sales_daily.
INSERT INTO orders (customer_id, order_date, total)
VALUES (1, CURRENT_DATE, 25.00);
SELECT *
FROM sales_daily
WHERE day = CURRENT_DATE;
REFRESH MATERIALIZED VIEW sales_daily;
SELECT *
FROM sales_daily
WHERE day = CURRENT_DATE;The first SELECT can show the old result, because the materialized view has not been refreshed. The REFRESH MATERIALIZED VIEW command reruns the aggregate query. The second SELECT then includes the new order.
A refresh replaces all stored rows. PostgreSQL does not update only the rows that changed in the base tables.
Locking during a refresh
The default refresh takes a strong lock on the materialized view. Queries that try to read it may wait until the refresh finishes. This behavior is often acceptable for a small view, but a large aggregate query can make the wait noticeable.
The lock applies to the materialized view, not directly to the base tables. Applications can usually continue writing to orders, although those writes may increase the time needed to complete the refresh.
Refreshing concurrently
REFRESH MATERIALIZED VIEW CONCURRENTLY allows other sessions to continue reading the old contents while PostgreSQL builds the new result. After the new result is ready, PostgreSQL makes it visible as a replacement.
Concurrent refresh has requirements:
- The materialized view must already be populated.
- It must have a unique index that covers all rows.
- The index must use plain column values, not expressions or a partial
WHEREcondition. - The defining query must produce values that make the index truly unique.
For the daily summary, each day should occur once, so a unique index is appropriate:
CREATE UNIQUE INDEX sales_daily_day_idx
ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;A concurrent refresh reduces read blocking, but it does more work and needs additional temporary space. It can also take longer than a standard refresh. It does not make the materialized view continuously current. Readers see the previous complete result until the refresh finishes.
| Refresh form | Reader behavior | Main requirement |
|---|---|---|
| `REFRESH MATERIALIZED VIEW` | Readers can wait for the refresh lock | No special index |
| `REFRESH MATERIALIZED VIEW CONCURRENTLY` | Readers continue using the old result | A suitable unique index |
Choosing a refresh strategy
Choose the refresh method based on freshness, query cost, and read availability:
- Use a standard refresh when the view is small or a short read pause is acceptable.
- Use a concurrent refresh when readers need uninterrupted access.
- Refresh after a known batch load when reports can tolerate batch-level freshness.
- Refresh periodically when the application needs predictable maximum staleness.
If the defining query is expensive, more frequent refreshes consume CPU, memory, and I/O. A materialized view is useful when avoiding repeated expensive reads is worth accepting delayed data.
Exercise
An order is inserted after the last refresh. Which command makes that order appear in the materialized view, and what extra requirement applies when readers must remain active?
Show answer
Run REFRESH MATERIALIZED VIEW. If readers must continue querying during the refresh, use REFRESH MATERIALIZED VIEW CONCURRENTLY and create a suitable unique index on the materialized view first.