Sub topic 3
Refreshing data with REFRESH MATERIALIZED VIEW
This chapter assumes you can create a materialized view with CREATE MATERIALIZED VIEW, and that you know basic transactions and locks in PostgreSQL. It covers what REFRESH MATERIALIZED VIEW does, what it locks, and the errors you are most likely to meet. Two later chapters cover CONCURRENTLY and WITH NO DATA in full. Here they appear only where they change how a plain refresh behaves.
Why a refresh is needed
A materialized view stores the rows its query produced when it was created or last refreshed. PostgreSQL does not track changes in the base tables, and it does not update the stored rows when those tables change. The view stays as it was until you ask for a refresh.
This chapter uses the orders table and sales_daily view from the previous chapter:
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;Insert a new order and compare the base table with the view:
INSERT INTO orders (customer_id, order_date, total)
VALUES (1, CURRENT_DATE, 25.00);
-- Still shows the old data:
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;
REFRESH MATERIALIZED VIEW sales_daily;
-- Now includes the new order:
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;The first SELECT returns no row for today, or a row without the new order. The second includes the order.
The syntax
The full form of the command is:
REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] name
[ WITH [ NO ] DATA ];The plain form, REFRESH MATERIALIZED VIEW sales_daily;, is the default. It is the same as WITH DATA. The WITH NO DATA form empties the view instead of filling it, and the WITH NO DATA chapter covers it.
What a refresh does internally
A plain refresh works in four steps:
- It takes an
ACCESS EXCLUSIVElock on the materialized view. - It runs the defining query again against the current data.
- It writes the result into a new, separate set of storage files.
- It swaps the new storage in for the old, rebuilds every index on the view, and commits.
This design has several consequences.
- The refresh is a full recomputation. PostgreSQL has no incremental refresh. If one order changed out of ten million, the whole aggregate still runs again. The cost is roughly the cost of the defining query plus writing the result and rebuilding the indexes.
- The refresh is transactional. If the query fails, for example from a timeout or a division by zero, the old contents stay in place. Readers never see a half-built view.
- Disk usage briefly doubles. The old and new copies exist side by side until the transaction commits. Check free space before refreshing a very large view.
- The view does not bloat. The new storage replaces the old, so refreshes do not leave dead rows behind the way repeated
UPDATEstatements would.
What data a refresh sees
The refresh runs the defining query with an ordinary snapshot. It includes rows committed before the query started and excludes uncommitted changes from other sessions. The following two-session sequence shows this:
-- Session A
BEGIN;
INSERT INTO orders (customer_id, order_date, total)
VALUES (2, CURRENT_DATE, 40.00);
-- not committed yet
-- Session B
REFRESH MATERIALIZED VIEW sales_daily;
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;
-- does not include the 40.00 order
-- Session A
COMMIT;
-- Session B: the view is still stale until the next refresh
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;
REFRESH MATERIALIZED VIEW sales_daily;
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;
-- now includes itA view is only as current as the last refresh's snapshot. A row committed one millisecond after the query began is missing until the next refresh.
Blocking and the lock queue
A plain refresh takes an ACCESS EXCLUSIVE lock. Every query that reads the view, including a simple SELECT, waits until the refreshing transaction commits or rolls back. For a view that takes 30 seconds to rebuild, readers wait up to 30 seconds. That is the reason CONCURRENTLY exists.
The lock also has a queueing effect:
- If a long-running
SELECTalready holds a lock on the view, the refresh waits for it. - While the refresh waits, new readers queue behind the refresh, even though the lock has not been granted yet.
- A single slow report can therefore stall every other reader of the view.
To limit this, set a lock_timeout so the refresh gives up instead of holding up the queue:
BEGIN;
SET LOCAL lock_timeout = '5s';
REFRESH MATERIALIZED VIEW sales_daily;
COMMIT;SET LOCAL applies the setting only to the current transaction. If the lock is not granted within five seconds, the refresh fails with a "canceling statement due to lock timeout" error. The job can then retry later.
To see who is waiting on a lock during a refresh, query pg_locks for the view's lock entries:
SELECT l.pid, l.mode, l.granted, a.state, left(a.query, 60) AS query
FROM pg_locks AS l
JOIN pg_stat_activity AS a ON a.pid = l.pid
WHERE l.relation = 'sales_daily'::regclass
ORDER BY l.granted DESC, l.pid;Rows with granted = false are the sessions that are waiting.
Measuring refresh cost
You cannot run EXPLAIN on a REFRESH statement. You can tune the defining query by running EXPLAIN (ANALYZE) on its SELECT part alone. To see the end-to-end time of the refresh itself, use psql's \timing:
\timing on
REFRESH MATERIALIZED VIEW sales_daily;Record that time for each view. It sets the lowest refresh interval you can sustain, and it is how long readers are blocked by a plain refresh.
After a large refresh, run ANALYZE on the view if your queries depend on accurate planner statistics:
ANALYZE sales_daily;Refresh order for dependent views
A materialized view can be built on another materialized view. Refreshing the upper view does not refresh the lower one. It only re-reads whatever the lower view currently holds.
CREATE MATERIALIZED VIEW sales_weekly AS
SELECT date_trunc('week', day)::date AS week,
sum(orders) AS orders,
sum(revenue) AS revenue
FROM sales_daily
GROUP BY 1;Refresh the lower view first, then the upper one. Do both in one transaction if you want readers to see a consistent pair:
BEGIN;
REFRESH MATERIALIZED VIEW sales_daily;
REFRESH MATERIALIZED VIEW sales_weekly;
COMMIT;In a single transaction, both views hold their exclusive locks until the commit. Readers of either view wait for the whole sequence. Separate transactions shorten each wait, but there is a short period where sales_weekly is older than sales_daily.
Permissions and the refresh context
Only the owner of the materialized view can refresh it, or a member of the owning role. A superuser can too. PostgreSQL 17 and later also let you grant the MAINTAIN privilege on the view to another role. A user who has only SELECT on the view cannot refresh it:
-- As a role that is not the owner:
REFRESH MATERIALIZED VIEW sales_daily;
-- ERROR: must be owner of materialized view sales_dailyThe defining query runs with the privileges of the view's owner, not of the person who issues the refresh. This is useful for scheduled jobs. A job role that owns the view needs read access to the base tables, and nobody else needs it.
In PostgreSQL 17 and later, the refresh also runs with a restricted search_path. Because of this, write functions and tables in the defining query with schema-qualified names, such as public.orders. This also makes the view's behavior independent of the session's settings.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `must be owner of materialized view` | The role issuing the refresh does not own the view. | Run the refresh as the owner, or as a member of the owning role. On PostgreSQL 17 or later you can grant `MAINTAIN`. |
| Readers hang during a refresh | The plain refresh holds an `ACCESS EXCLUSIVE` lock. | Use `CONCURRENTLY` (a later chapter), or refresh when load is low. |
| Refresh waits and other queries pile up | A long query holds a lock on the view, and new readers queue behind the waiting refresh. | Set `lock_timeout`, and find the long query in `pg_stat_activity`. |
| `materialized view "x" has not been populated` on `SELECT` | The view was created or refreshed with `WITH NO DATA`. | Run `REFRESH MATERIALIZED VIEW x;`. |
| A view built on another view shows old data | The lower view was not refreshed first. | Refresh in dependency order. |
| `canceling statement due to statement timeout` | The refresh query runs longer than `statement_timeout`. | Raise the timeout for the refresh job, or speed up the defining query. The old contents stay in place. |
| `could not extend file` or disk full | The old and new copies need space at the same time. | Free disk space, or reduce the size of the view. |
Because a failed refresh rolls back, the view keeps its previous contents after any of these errors. You get stale data, not missing data.
Checking when a view was last refreshed
PostgreSQL does not record the time of the last refresh. pg_matviews shows whether the view is populated, but not how old the data is. If your application needs to know, store the timestamp yourself, for example in a small table that the refresh job updates in the same transaction:
CREATE TABLE IF NOT EXISTS matview_refresh_log (
view_name text PRIMARY KEY,
refreshed_at timestamptz NOT NULL
);
BEGIN;
REFRESH MATERIALIZED VIEW sales_daily;
INSERT INTO matview_refresh_log (view_name, refreshed_at)
VALUES ('sales_daily', now())
ON CONFLICT (view_name) DO UPDATE SET refreshed_at = EXCLUDED.refreshed_at;
COMMIT;Readers can then show "data as of" next to a report, and monitoring can alert when refreshed_at is too old.
Summary of key behaviors
REFRESH MATERIALIZED VIEWre-runs the defining query in full and replaces the stored rows.- The plain form blocks all readers with an
ACCESS EXCLUSIVElock until it commits. - A failed refresh leaves the old contents untouched.
- The view reflects only data committed before the refresh query began.
- Only the owner can refresh, and the query runs with the owner's privileges.
- Dependent materialized views must be refreshed in order, and PostgreSQL does not track the last refresh time for you.
Exercise
You run REFRESH MATERIALIZED VIEW sales_weekly;, where sales_weekly is built on sales_daily. New orders were inserted into orders an hour ago, and sales_daily has not been refreshed since. Will sales_weekly include those orders? Also, a colleague's long report is reading sales_weekly at the moment you start the refresh. What happens to other users who query sales_weekly while your refresh waits?
Show answer
No. sales_weekly reads from sales_daily, which still holds the old rows, so the new orders are missing. You must refresh sales_daily first and then sales_weekly. While your refresh waits for the report to release its lock, new readers of sales_weekly queue up behind your refresh, because it is waiting for an ACCESS EXCLUSIVE lock. Setting lock_timeout in the refreshing transaction lets it give up instead of holding up the queue.
Exercise
A refresh of a large view fails halfway through because of a statement_timeout. What does a SELECT on the view return afterward?
Show answer
It returns the contents from before the failed refresh. The refresh is transactional, so the failure rolls it back and the old storage stays in place. The data is stale, but it is complete and consistent.