Sub topic 12
Refreshing a materialized view
This chapter assumes you can write GROUP BY queries, know that a materialized view stores its query result on disk, and have used CREATE INDEX. The examples use PostgreSQL syntax. Oracle and MySQL differ, and the differences are covered below.
Why a refresh is needed
A regular view runs its query every time you read it. A materialized view runs the query once, stores the rows, and serves later reads from that stored copy. Reads are fast, but the copy does not follow changes to the base tables. The database never refreshes it on its own. Until someone refreshes it, the view shows the data as of the last refresh.
The following sequence shows this with the department_salary_totals view from the earlier chapter. It assumes that view exists and that the department ids 10 and 100 below are unused.
INSERT INTO departments (id, name) VALUES (10, 'Engineering');
INSERT INTO employees (id, name, salary, status, department_id)
VALUES (100, 'Cleo', 6000, 'active', 10);
-- The new employee is not counted yet. This returns no row for department 10.
SELECT * FROM department_salary_totals WHERE department_id = 10;
REFRESH MATERIALIZED VIEW department_salary_totals;
-- Now the row appears, with total_salary 6000.
SELECT * FROM department_salary_totals WHERE department_id = 10;REFRESH MATERIALIZED VIEW re-executes the stored query and replaces the stored rows with the new result. It is a full recompute. The cost is roughly the cost of the original query, however few rows changed.
What a plain refresh does
In PostgreSQL, a plain REFRESH MATERIALIZED VIEW builds the new result and swaps it in. It takes an ACCESS EXCLUSIVE lock on the view for the whole operation. That lock has three consequences:
- Any
SELECTon the view waits until the refresh finishes. - If the refresh itself has to wait for a long-running reader, new readers queue behind the refresh. A single slow query can therefore stall every other reader.
- The refresh runs in one transaction. If the underlying query fails, for example from a division by zero, the old contents stay in place and readers see the previous data.
Only the owner of the materialized view can refresh it. If a scheduled job runs as a different role, grant that role membership in the owning role, or run the job as the owner.
Refreshing without blocking readers
Adding CONCURRENTLY lets readers keep using the old contents while the refresh runs. PostgreSQL computes the new result into a temporary table, compares it with the stored rows, and applies only the differences (inserts, updates and deletes). Readers see either the old data or the new data, never a partial state.
This mode has a requirement. The view must have at least one unique index that covers plain columns, with no expressions and no WHERE clause. PostgreSQL uses it to match old rows with new ones.
CREATE UNIQUE INDEX department_salary_totals_dept_idx
ON department_salary_totals (department_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY department_salary_totals;In this view, department_id is unique because the query groups by it. Employees with a NULL department fall into a single group, so the index still holds.
The trade-offs of CONCURRENTLY:
- It is usually slower than a plain refresh, because it builds a temporary copy and runs the comparison.
- It only works on a view that already holds data. The first population must use a plain refresh.
- Two refreshes of the same view cannot run at the same time. The second waits for the first.
- Writers are not an issue, since nobody writes to a materialized view directly. Only the refresh changes it.
If the view does not have a suitable unique index, PostgreSQL rejects the command with an error that names the missing index.
Creating the view empty
You can define a materialized view without running its query. This is useful in migration scripts, where you want the object to exist before the data is ready.
CREATE MATERIALIZED VIEW department_salary_totals_empty AS
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
WITH NO DATA;
-- Fails: the materialized view has not been populated.
SELECT * FROM department_salary_totals_empty;
-- Populates it. A plain refresh is required for the first load.
REFRESH MATERIALIZED VIEW department_salary_totals_empty;You can also run REFRESH MATERIALIZED VIEW name WITH NO DATA on an existing view. That empties it and makes it unreadable again until the next refresh, which frees its storage. WITH NO DATA cannot be combined with CONCURRENTLY.
Choosing when to refresh
PostgreSQL has no built-in schedule and no refresh trigger. You decide when the refresh runs, and the usual options are these:
| Approach | How it works | Staleness | Cost |
|---|---|---|---|
| Manual | A person or deploy script runs the command | Unbounded | None until used |
| External scheduler | `cron`, a job runner or the application issues the command | Up to the interval | One full recompute per run |
| `pg_cron` extension | The schedule lives inside the database | Up to the interval | One full recompute per run |
| Trigger on base tables | A trigger runs the refresh after writes | Near zero | A full recompute per write statement |
The last row is rarely a good idea. A trigger that runs a full refresh after every write makes each write as slow as the whole aggregation, and it holds locks for that time. If you need up-to-the-second data, use a regular view, or maintain a summary table incrementally yourself.
With the pg_cron extension installed, a job can look like this:
SELECT cron.schedule(
'refresh-department-totals',
'*/15 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY department_salary_totals'
);This runs every 15 minutes. Pick the interval from the freshness your readers can tolerate, then check that a refresh takes much less time than the interval. If the refresh takes longer than 15 minutes, runs pile up behind each other.
How other systems refresh
The statement names and capabilities differ between database systems.
Oracle supports several refresh modes, chosen when the view is created. REFRESH COMPLETE re-runs the whole query. REFRESH FAST applies only the changes recorded in a materialized view log on the base tables, which can be far cheaper for large tables. Fast refresh has restrictions on the query, for example aggregate views need extra COUNT columns. ON COMMIT refreshes the view when a transaction that changed the base tables commits, and ON DEMAND refreshes it only when asked.
-- Oracle
CREATE MATERIALIZED VIEW department_salary_totals
REFRESH COMPLETE ON DEMAND
AS
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;
-- Refresh on demand. The 'C' means a complete refresh.
BEGIN
DBMS_MVIEW.REFRESH('DEPARTMENT_SALARY_TOTALS', 'C');
END;
/MySQL has no native materialized views. The common substitute is a regular table that holds the summary, filled by a scheduled EVENT or an external job that truncates and reloads it, or inserts new rows and deletes old ones inside a transaction. You build the refresh logic yourself.
Common errors
- "has not been populated": the view was created or refreshed
WITH NO DATA. Run a plain refresh. CONCURRENTLYrejected because of a missing unique index: add a unique index on plain columns, with no expression orWHEREclause.CONCURRENTLYon an unpopulated view: run one plain refresh first.- "must be owner": the role running the refresh does not own the view.
- Readers hang during a refresh: a plain refresh holds an exclusive lock. Switch to
CONCURRENTLYor schedule the refresh for a quiet period. - Overlapping scheduled refreshes: the interval is shorter than the refresh time. Lengthen the interval or speed up the underlying query.
Exercise
A materialized view daily_sales is read by a dashboard all day. A nightly job runs REFRESH MATERIALIZED VIEW daily_sales, and users report the dashboard freezing for several minutes at night. What change fixes this, and what must the view have before the change works?
Show answer
Change the job to REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales, so readers keep seeing the old rows during the refresh instead of waiting on an ACCESS EXCLUSIVE lock. Before it works, the view must already hold data and have at least one unique index on plain columns (no expressions, no WHERE clause).
Exercise
You add an AFTER INSERT trigger on employees that runs a refresh of department_salary_totals after every statement, to keep the totals always current. Name two problems with this design.
Show answer
Each insert now pays for a full recompute of the aggregation, so write speed drops to the speed of the whole query. A plain refresh also takes an exclusive lock, so readers of the view block on every write, and concurrent writers queue behind each other's refreshes. A regular view or an incrementally maintained summary table fits this need better.