Sub topic 11
Materialized views: storing the result
This chapter assumes you can write SELECT queries with JOIN and GROUP BY. It also assumes you know how a regular view works: a named query that the database expands into the queries that use it. The examples use PostgreSQL syntax and the departments and employees tables from earlier chapters. Where Oracle, MySQL or SQL Server differ, the text says so.
Regular views recompute, materialized views remember
A regular view stores only a query. Each time you select from it, the database runs that query against the base tables. The result is always current, but you pay the full cost of the join or aggregation on every read.
A materialized view stores the query and also its result. The database runs the query once, when you create the view or refresh it, and writes the rows to disk like a table. Later reads scan those stored rows and do not touch the base tables.
| Property | Regular view | Materialized view |
|---|---|---|
| Stores rows on disk | No | Yes |
| Read cost | Cost of the full query | Cost of scanning stored rows |
| Freshness | Always current | As of the last refresh |
| Can have its own indexes | No | Yes (in PostgreSQL and Oracle) |
| Accepts `INSERT`, `UPDATE`, `DELETE` | Sometimes (updatable views) | No, you can only refresh it |
| Uses extra storage | No | Yes |
The trade is storage and freshness in exchange for read speed.
Creating a materialized view
Suppose reporting needs total salary per department, and the employees table is large. Recomputing the sum for every dashboard load wastes work, because the answer changes rarely.
CREATE MATERIALIZED VIEW department_salary_totals AS
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;In PostgreSQL this statement runs the query immediately and fills the view. You then query it like any table:
SELECT * FROM department_salary_totals ORDER BY department_id;Everything you learned about naming view columns applies here too. You can write a column list after the view name, or use aliases such as total_salary above.
Creating without data
PostgreSQL lets you create the definition now and fill it later:
CREATE MATERIALIZED VIEW department_salary_totals AS
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id
WITH NO DATA;A view created WITH NO DATA is unpopulated. Selecting from it raises an error until you run REFRESH MATERIALIZED VIEW. This is useful in migration scripts, where you want to create the object without paying for a heavy query during deployment. Oracle expresses the same choice with BUILD IMMEDIATE and BUILD DEFERRED.
Seeing staleness for yourself
The stored result does not follow changes in the base tables. This script shows it, starting from empty departments and employees tables.
INSERT INTO departments (id, name) VALUES (1, 'Engineering'), (2, 'Sales');
INSERT INTO employees (id, name, email, salary, status, department_id) VALUES
(1, 'Ana', '[email protected]', 5000, 'active', 1),
(2, 'Ben', '[email protected]', 4800, 'active', 1),
(3, 'Cy', '[email protected]', 4000, 'active', 2);
CREATE MATERIALIZED VIEW department_salary_totals AS
SELECT department_id,
SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;
SELECT * FROM department_salary_totals ORDER BY department_id;
-- department 1: 9800.00, department 2: 4000.00
INSERT INTO employees (id, name, email, salary, status, department_id)
VALUES (4, 'Dee', '[email protected]', 6000, 'active', 2);
SELECT * FROM department_salary_totals ORDER BY department_id;
-- Still 9800.00 and 4000.00. The new salary is not counted.
REFRESH MATERIALIZED VIEW department_salary_totals;
SELECT * FROM department_salary_totals ORDER BY department_id;
-- Now 9800.00 and 10000.00.Between the insert and the refresh, the view gives a consistent answer that is out of date. Nothing warns the reader. If your application cannot tolerate that, a materialized view is the wrong tool for that query.
Refreshing, briefly
REFRESH MATERIALIZED VIEW name re-runs the defining query and replaces the stored rows. The next chapter covers refresh strategies in detail. Two points matter now:
- A plain refresh in PostgreSQL takes a lock that blocks readers of the view until it finishes. For a long query, that can stall dashboards.
- PostgreSQL offers
REFRESH MATERIALIZED VIEW CONCURRENTLY, which avoids blocking readers. It needs a unique index on the view and is slower than a plain refresh.
Oracle has a richer model. A view can refresh on demand, on a schedule, or automatically at each commit of a base-table transaction (REFRESH ON COMMIT). It can also refresh incrementally using materialized view logs.
Indexing a materialized view
A regular view has no storage, so you cannot index it. You index the base tables and hope the optimizer uses those indexes. A materialized view is stored, so you can index it directly. This is often the larger benefit.
CREATE UNIQUE INDEX department_salary_totals_dept_idx
ON department_salary_totals (department_id);With this index, a lookup of one department's total reads one index entry. It does not scan the employees table. The index must be rebuilt as part of each refresh, which adds to refresh time, so add only the indexes your queries use.
Where the stored result pays off
Materialized views fit queries that are expensive and read often, and whose answers can be somewhat out of date:
- Aggregations over large tables, such as daily totals, counts by category, and top-N lists.
- Joins across many tables that are shared by several reports.
- Data fetched through a slow source, such as a foreign table. Reading the stored copy avoids the remote call.
They fit poorly when:
- Readers must see the result of a write immediately.
- The base data changes constantly and the refresh costs about as much as the reads it saves.
- The result is large and nobody reads it often, so the storage buys little.
A rough test is to compare the refresh cost and refresh frequency against the number of reads and the cost of each read. If a refresh runs once an hour and the view is read thousands of times in that hour, the stored copy saves a great deal.
Differences between database systems
Materialized views are not part of core standard SQL, and support varies.
| System | Support |
|---|---|
| PostgreSQL | `CREATE MATERIALIZED VIEW`, manual `REFRESH`, optional `CONCURRENTLY`. No automatic refresh and no incremental refresh in the core product. |
| Oracle | Full support, including refresh on commit, scheduled refresh, incremental (fast) refresh, and query rewrite. |
| MySQL | No native materialized views. You build a summary table and refresh it yourself, using scheduled events or application code. |
| SQL Server | No `MATERIALIZED` keyword. An *indexed view* (a view with a unique clustered index) is stored and kept current automatically on each write, subject to restrictions on the query. |
The SQL Server design shows another point on the trade-off. It keeps the stored result always fresh, and every write to the base tables pays for that. PostgreSQL's design keeps writes cheap and lets the result go stale.
Common errors
- Writing to the view.
INSERT,UPDATEandDELETEon a materialized view fail in PostgreSQL. Change the base tables and refresh. - Selecting from an unpopulated view. A view created
WITH NO DATAraises an error until its first refresh. - Forgetting the refresh. The most common bug is a view that was correct when it was created and has been wrong ever since. Schedule the refresh, and monitor how long ago it last ran.
- Refreshing concurrently without a unique index.
REFRESH ... CONCURRENTLYfails if the view has no suitable unique index. - Dropping a base table or column. The database blocks this while the view depends on it. You must drop the view first, or use
DROP ... CASCADEand accept that the view is removed too. - Treating it like a security boundary without checking. Privileges on a materialized view are separate from those on the base tables. Granting
SELECTon the view exposes the stored rows as of the last refresh. Revoking access to a base table does not remove rows already stored.
To remove a materialized view, use its own statement:
DROP MATERIALIZED VIEW IF EXISTS department_salary_totals;A plain DROP VIEW does not work on a materialized view in PostgreSQL.
Finding materialized views in the catalog
In PostgreSQL, information_schema.views lists regular views only. Materialized views appear in the system catalog pg_matviews:
SELECT schemaname, matviewname, ispopulated
FROM pg_matviews
WHERE schemaname = 'public';The ispopulated column tells you whether the view has been filled, which helps you spot views created WITH NO DATA that nobody refreshed.
Exercise
A report page reads the total salary per department about 5,000 times an hour. The employees table has 20 million rows, and salaries change a few times a day. You create department_salary_totals as a materialized view and refresh it once a day at midnight. A manager raises a salary at 10:00 and checks the report at 10:05. What total do they see, and what are two ways to reduce the delay?
Show answer
They see the total from the midnight refresh, which does not include the raise. To reduce the delay, refresh more often, for example hourly, so that the cost stays small compared with the 5,000 reads. Alternatively, trigger a refresh after salary changes, or use a regular view (or a query on an indexed base table) for this report if immediate accuracy matters more than read speed.
Exercise
You run CREATE MATERIALIZED VIEW sales_by_day AS SELECT ... WITH NO DATA; in a deployment script. Right after the script, a user runs SELECT * FROM sales_by_day; and gets an error. What happened, how do you fix it, and how can you check the state in PostgreSQL?
Show answer
The view is unpopulated, so it has no stored rows and cannot be read. Run REFRESH MATERIALIZED VIEW sales_by_day; to populate it. To check, query pg_matviews and look at the ispopulated column, which is false for this view before the refresh.
Exercise
Why can you create an index on a materialized view but not on a regular view, and what does the index cost you?
Show answer
A materialized view stores its rows, so an index has data to point to. A regular view stores only a query, so there is nothing to index. The cost is extra storage and extra work on each refresh, because the index must be rebuilt or updated with the new rows.