Skip to main content

How Materialized Views Work

What is a Materialized View?

A materialized view (MV) is a database object that stores the result of a query physically on disk — unlike a regular view, which is just a saved query that re-executes every time. Think of it as a cached snapshot of expensive query results.

When to Use Materialized Views

Use CaseWhy MV Helps
Dashboards & reportsPrecompute expensive aggregations
Multi-table JOINsStore joined result, avoid repeated JOINs
Data warehousingPre-aggregate star-schema queries
Rankings & percentilesCache expensive window functions

When NOT to Use

  • Real-time OLTP where data must be current
  • Small datasets where regular queries are fast enough
  • When write throughput is already a bottleneck (MV adds storage + refresh cost)

Visualization

Switch between the three scenarios to see the full lifecycle:

  • Build MV: Watch how source tables are scanned, aggregated, and written to disk
  • Query Comparison: See the dramatic difference between live queries and MV reads
  • Refresh MV: See what happens when source data changes and the MV needs updating
0 / 10
Source Tables (customers + orders)
-- Source data (customers + orders joined) -- This is what the MV precomputes
IDCustomerOrdersTotalAvg
1Emma12$2,400$200
2Liam5$750$150
3Sophia28$8,400$300
4Noah3$270$90
5Olivia15$3,750$250
6James8$1,600$200
7Alice42$12,600$300
8Bob1$45$45
Materialized View (precomputed)
CREATE MATERIALIZED VIEW mv_customer_summary AS SELECT c.id, c.name, COUNT(o.id), SUM(o.amount), AVG(o.amount) FROM customers c JOIN orders o ...
MV Definition
Scan Sources
Aggregate
Write to Disk
Ready to Query
MV is stale — data not yet computed
Press Play to start building the materialized view...

Key Concepts

MV vs Regular View

AspectRegular ViewMaterialized View
StorageVirtual (no storage)Physical disk storage
Read speedSlow (recomputes)Fast (precomputed)
Data freshnessAlways currentStale until refreshed
Write overheadNoneExtra storage + refresh cost

Refresh Strategies

Database Support

DatabaseAuto-RefreshIncrementalNotes
PostgreSQLManualNo (full rebuild)REFRESH MATERIALIZED VIEW
OracleYesYes (MV Logs)Most mature implementation
SQL ServerAuto (live)N/A"Indexed Views" — schema-binding required
ClickHouseAutoYesCore feature for real-time analytics

Common Pitfalls

PitfallSolution
Stale dataSet up scheduled refresh with pg_cron
Full rebuild costUse REFRESH CONCURRENTLY (PostgreSQL)
Missing unique indexCreate one — required for concurrent refresh
Storage bloatMonitor MV size, drop unused views

Learn More

Read the full theory in Database Design and SQL Fundamentals.