Materialized Views & Updatable Views in SQL
Precompute for speed; guard writes with CHECK OPTION
Ordinary views run fresh per use — always current. Materialized views store results physically — table-fast reads, freshness costs REFRESH (on-demand, scheduled, incremental). Simple single-table views are updatable (writes pass through), optionally guarded by WITH CHECK OPTION (rejects rows that would vanish). Complex views need INSTEAD OF triggers.
View is a saved query
Runs fresh per use — always current, cost paid per read.
Matview stores results
Physically persisted — table-fast reads, REFRESH cost for freshness.
Staleness decides
Dashboards/rollups over slow-changing data: yes. Balances/fresh reads: no.
Updatable + temp siblings
Simple views accept writes (+ CHECK OPTION guard). TEMP tables serve cross-statement heavies with indexes.
1CREATE MATERIALIZED VIEW dept_stats AS SELECT department, COUNT(*) AS n FROM employees GROUP BY department;2REFRESH MATERIALIZED VIEW dept_stats;
| department | n |
|---|---|
| Engineering | 3 |
| Sales | 2 |
| Marketing | 1 |
The rollup is precomputed once and read like a table. New hires do not appear until REFRESH — that staleness is the price of speed. Temp tables serve the same need across statements with indexes.
Precomputed rollup
Expensive agg paid once, read many times.
1CREATE MATERIALIZED VIEW dept_stats AS SELECT department, COUNT(*), AVG(salary) FROM employees GROUP BY department;2REFRESH MATERIALIZED VIEW dept_stats;
| department | count |
|---|---|
| Engineering | 3 |
| Sales | 2 |
| Marketing | 1 |
Guarded updatable view
Writes that would vanish are rejected.
1CREATE VIEW eng AS SELECT * FROM employees WHERE department = 'Engineering' WITH CHECK OPTION;
| guard | rule |
|---|---|
| WITH CHECK OPTION | inserts must satisfy predicate |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.