Sub topic 11
Materialized Views: Storing the Result
This chapter assumes you can write SELECT queries with joins and aggregates, create regular views, and understand basic indexes and transactions. You will learn when to store a query result instead of calculating it for every read.
A materialized view stores data
A regular view stores a query definition. When you query it, the database usually expands that definition into the surrounding query and reads the current base tables.
A materialized view stores the result of its query, often on disk. A read can therefore use precomputed rows instead of repeating an expensive join or aggregation.
| Object | Stores | Read freshness | Typical use |
|---|---|---|---|
| Regular view | Query definition | Current base-table data | Reusable queries and access control |
| Materialized view | Query result | Last refresh | Reports and expensive summaries |
A materialized view is still derived data. Changes to the underlying tables do not automatically change its stored rows.
Creating a materialized view
The exact syntax differs between database systems. PostgreSQL and Oracle support materialized views, but their refresh options and concurrency rules differ. This example uses PostgreSQL syntax.
CREATE MATERIALIZED VIEW department_salary_totals AS
SELECT department_id,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary
FROM employees
WHERE status = 'active'
GROUP BY department_id;The database runs the query when it creates the materialized view and stores the returned rows. You can query those rows like a table:
SELECT department_id,
employee_count,
total_salary
FROM department_salary_totals
WHERE total_salary > 100000
ORDER BY total_salary DESC;A materialized view can often have indexes. Indexes are especially useful when the stored result is large and reports filter or sort it repeatedly.
CREATE INDEX department_salary_totals_salary_idx
ON department_salary_totals (total_salary);Creating an index does not make the stored result current. It only makes searches over the current stored result faster.
Refreshing the stored result
Use REFRESH MATERIALIZED VIEW to run the defining query again and replace the stored rows.
REFRESH MATERIALIZED VIEW department_salary_totals;After employees are added or salaries change, the materialized view remains unchanged until this command runs. A scheduled job might refresh it every hour, every night, or after a reporting batch completes.
PostgreSQL also supports concurrent refreshes when the materialized view has a suitable unique index:
CREATE UNIQUE INDEX department_salary_totals_department_id_idx
ON department_salary_totals (department_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY department_salary_totals;A concurrent refresh can allow readers to continue using the old result while the new result is prepared. It has extra requirements and may take more work, so check your database documentation before choosing it.
Choosing a materialized view
Use one when the defining query is expensive, the same result serves many readers, and delayed updates are acceptable. Avoid one when users need transaction-level freshness or when the source data changes too often for refreshes to be worthwhile.
Consider these costs:
- The database uses storage for the result and its indexes.
- Refreshing consumes CPU, memory, and I/O.
- A full refresh may temporarily compete with application traffic.
- The result can be misleading if users do not know its refresh time.
- Schema changes to source tables can invalidate the defining query.
Record or display the last successful refresh time when freshness matters. Treat refresh scheduling as part of the materialized view's design, not as an afterthought.
Exercise
The employees table changed five minutes ago. A report reads departmentsalarytotals and shows the old total. What operation is missing?
Show answer
The materialized view needs to be refreshed. In PostgreSQL, run REFRESH MATERIALIZED VIEW departmentsalarytotals, or schedule an appropriate refresh job.