SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Materialized Views

Save the answer of a heavy query as a table, and refresh it when needed.

โฑ 11 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A materialized view is the saved result of a query, stored like a table. Reading it is fast because the heavy work was already done. The cost is that it can get stale, so you must refresh it.

  • A normal view is only a saved query. It runs again on every read.
  • A materialized view stores the rows. Reads are cheap, writes (refreshes) pay the bill.
  • The key choice is when and how to refresh: how fresh does the data need to be, and how much work can you afford?

02Concept: What is it?

Some queries are heavy: they join big tables, group, sum and sort millions of rows. A dashboard that runs one on every page load will drown the database. But the answer changes slowly, and many people ask for the same answer. So we compute it once and keep it. That kept answer is a materialized view.

View vs materialized view
View (virtual)
๐Ÿ‘€Read
โ†“runs the query every time
๐ŸŒBase tablesjoin + group + sum
Materialized view (stored)
๐Ÿ‘€Read
โ†“reads saved rows
๐Ÿ“ฆStored resultrefreshed now and then
โ†‘refresh
๐Ÿ—„๏ธBase tables
Both look like a table to the reader. The difference is where the work happens.

Think of it as a cache that lives inside the database, defined by a query. You get the benefits of precomputing without writing your own summary table and sync code.

๐Ÿง The central question
How stale can this be? If five minutes old is fine, you can refresh rarely and save a lot. If it must be live, a materialized view may not be the right tool.

03Real-Life Example

๐ŸตThe Shop's Daily Sales Board
A shop owner wants to know "sales per product this month". To work it out, an assistant must go through every receipt. That takes an hour. Asking 50 times a day would be silly. So each morning the assistant makes a one-page summary and pins it on the board. Anyone can read it in a second. It is correct as of this morning. If the owner needs live numbers, the assistant must update the board more often, which costs more effort.
Sales board
Materialized view
All the receipts
The base tables
Going through every receipt
Running the heavy query
The pinned one-page summary
The stored result
Reading the board in a second
Reading the materialized view
Making a new summary
REFRESH
Only adding today's new receipts to the board
Incremental refresh
The board says 'as of this morning'
Staleness
Refresh cycle
๐ŸงพWritesorders arrive
โ†’โ†“base table changes
โฐRefresh triggertimer, event, commit
โ†’โ†“re-run query
๐Ÿ“ฆMaterialized viewfresh again
โ†’โ†“fast reads
๐Ÿ“ŠDashboard
The stored result is rebuilt on a schedule or by a trigger.

04Why Do We Need It?

โšกFast reads
A heavy join and group becomes a simple table read.
๐Ÿ›ก๏ธProtect the database
Many dashboard users no longer run the heavy query.
๐ŸงฎPrecompute once
Pay for the work once per refresh, not once per reader.
๐Ÿ”Index the result
You can add indexes to the view, so even filtering the summary is quick.
๐ŸงฐLess app code
The database defines and refreshes it. No custom summary job to write.
๐ŸงฉA simpler alternative to denormalizing
Keep tables clean, and let the view hold the pre-joined shape.
If many people read the same expensive answer that changes slowly, store the answer.

05Where Do We Use It?

๐Ÿ“ŠDashboards and reports
Sales by day, active users by week, revenue by region.
๐Ÿ†Leaderboards and top-N lists
Top products, top posts, trending items.
๐Ÿ”ขCounts and totals
Followers, orders per customer, stock by warehouse.
๐Ÿ”—Pre-joined data
A wide table for search pages built from many tables.
๐ŸฌData warehouses
Aggregates over huge fact tables (BigQuery, Snowflake, Redshift).
๐Ÿ”ŒRemote or slow sources
Keep a local copy of data from another database or a foreign table.

06Types / Parts / How It Works

Ways to refresh

StrategyHow it worksGood and bad
Full refreshDelete the stored result and run the whole query again (REFRESH MATERIALIZED VIEW).Simple and always correct as of that moment. Costs the full query each time. In PostgreSQL, the plain form locks reads while it runs, and CONCURRENTLY avoids that but needs a unique index.
Incremental refreshApply only the rows that changed since the last refresh (a delta).Much cheaper. Needs support from the engine, or a change log, and more complex logic.
On commitThe view is updated inside each write transaction.Never stale. Every write is slower and holds locks longer.
On demandA person or a deploy runs the refresh.Simple. Easy to forget.
ScheduledA job (cron, scheduler) refreshes every N minutes or each night.Predictable cost. Staleness up to the interval.
Event-drivenA change stream triggers refresh or updates the stored rows.Near real time. More moving parts.
Plain view
a saved query
  • No stored data, no extra space
  • Always fresh
  • Runs the full query on every read
  • Good for hiding complexity, not for speed
Materialized view
a saved result
  • Stores rows on disk
  • Fast reads, can be indexed
  • Can be stale between refreshes
  • Needs a refresh plan
Freshness against cost
Plain viewfresh, very costly reads
On commitfresh, slower writes
Every minutealmost fresh
Every hourup to 1 hour old
Nightlyup to 1 day old, cheapest
Costly Cheap
The more often you refresh, the fresher the data and the higher the cost. Pick the cheapest point that is fresh enough.
Example (PostgreSQL style)
CREATE MATERIALIZED VIEW daily_sales AS
SELECT date_trunc('day', created_at) AS day,
       product_id,
       SUM(amount) AS revenue,
       COUNT(*)    AS orders
FROM orders
GROUP BY 1, 2;

-- a unique index lets you refresh without blocking readers
CREATE UNIQUE INDEX ON daily_sales (day, product_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;
VisualizerPlain view vs materialized view, and refresh strategiesStart with the plain view and note the total work. Switch to Full refresh and slide the interval. Then try Incremental and On every commit, and watch staleness against cost.
How is the result kept?

REFRESH MATERIALIZED VIEW rebuilds everything from scratch at a set interval. Simple. The result is stale between refreshes.

How old the stored result is at each second of one minute (taller = more stale; dots mark a refresh). Base table: 1.0M rows.
0 s30 s60 s
Staleness now
0 s
worst: 9 s, average 4.5 s
Total work (1 min)
6.0k
reads 1.2k + refresh 4.8k + writes 0
Saving vs plain view
99%
Refreshes
6
Plain view960k
This choice6.0k
A full refresh every 10 seconds costs 4.8k units, and reads cost 1.2k. Total is 99% less than running the query on every read. Readers see data up to 9 seconds old.

A simplified model with a simulated clock and abstract work units (no random numbers). Real refresh cost depends on the engine: PostgreSQL rebuilds fully (REFRESH MATERIALIZED VIEW), while Oracle, SQL Server (indexed views), Snowflake and others can maintain some views incrementally. Check what your database supports.

07How to Use It / Steps / Implementation

Using a materialized view well

  1. 1
    Find a heavy, repeated query
    Many readers, an expensive aggregate or join, and an answer that changes slowly.
  2. 2
    Ask how fresh it must be
    Seconds, minutes, hours? This sets the refresh plan.
  3. 3
    Create the view
    Use the exact query. Keep it small: store only the columns you need.
  4. 4
    Add indexes on the view
    Index the columns that readers filter or sort by. A unique index also enables non-blocking refresh in PostgreSQL.
  5. 5
    Choose the refresh method
    Scheduled full refresh to start. Move to incremental or event-driven only if the refresh itself is too heavy or too slow.
  6. 6
    Refresh without blocking readers
    Use a concurrent or swap-based refresh so dashboards do not freeze.
  7. 7
    Show freshness to users
    Display "Updated 5 minutes ago". It sets honest expectations.
  8. 8
    Monitor
    Track refresh duration, failures and size. A silent failed refresh means silently old data.
โš ๏ธA failed refresh is invisible
If the nightly job fails, readers keep seeing yesterday's numbers and nothing looks broken. Alert on the last successful refresh time.
Typical goal: refresh time vs refresh intervalthe refresh should finish well within its interval

08Key Terms to Know

TermMeaning in easy words
ViewA saved query that runs each time you read it
Materialized viewA saved query whose result is stored as rows
RefreshUpdating the stored result from the base tables
StalenessHow old the stored data is compared with the real data
Full refreshRebuilding the whole result from scratch
Incremental refreshApplying only the changes since the last refresh
Delta / change logThe list of rows that changed
Concurrent refreshA refresh that does not block readers
Base tableThe original table the view is built from
Query rewriteThe optimizer silently using a materialized view to answer a query (Oracle, Snowflake and others)
Rollup / summary tableA hand-made table of precomputed totals

09Pros, Cons and Trade-offs

โœ… Pros
  • Fast reads for heavy queries
  • Takes load off the main tables
  • Can be indexed
  • Defined in SQL, no extra app code
  • Keeps base tables clean and normalized
โš ๏ธ Cons
  • Data can be stale
  • Uses extra storage
  • Refresh costs CPU and I/O, and may lock
  • Not every database supports incremental refresh
  • A failed refresh can go unnoticed
  • Not suitable when you need live exact data

Trade-offs

ChoiceWe gainWe lose
Refresh oftenFresher dataMore refresh work and load
Refresh rarelyCheapOlder data
Full refreshSimple, always correctCost grows with table size
Incremental refreshCost grows with change size, not table sizeComplex, limited query shapes
Refresh on commitNever staleSlower writes, more locking
Plain view insteadAlways fresh, no storageSlow reads

10Common Problems and Mistakes

Common mistakes

  1. Using it for data that must be live. Balances and stock counts at checkout need the real rows.
  2. A blocking refresh at peak time. Readers wait while the view is rebuilt. Use a concurrent refresh.
  3. No alert on refresh failure. Stale data hides for days.
  4. Refreshing too often. A refresh that takes 5 minutes, run every minute, never ends.
  5. Storing too much. A materialized view with every column is a copy of the table. Keep it focused.
  6. Forgetting indexes on the view. The view is a table. Without indexes, big reads are still scans.
  7. Stacking views on views. Refresh order and cost become hard to reason about.

Things to watch

๐Ÿ”’Locks during refresh
A plain refresh in some engines blocks reads until it finishes.
๐Ÿ“ˆRefresh cost grows
As the base table grows, a full refresh gets slower. Plan for incremental refresh.
๐Ÿ”Permissions
Row-level security on the base tables may not apply to the stored view. Check access rules.
๐ŸงญDifferent per engine
Syntax and features vary a lot. Read your database docs.

11Real-World Examples

๐Ÿ˜PostgreSQL
CREATE MATERIALIZED VIEW and REFRESH (optionally CONCURRENTLY). Refresh is full; extensions or custom code provide incremental behaviour.
๐Ÿ›๏ธOracle
Materialized views with fast (incremental) refresh using change logs, and query rewrite.
๐ŸชŸSQL Server
Indexed views are stored and maintained automatically on each change.
โ„๏ธSnowflake and BigQuery
Managed materialized views refreshed automatically in the background (with query shape limits).
๐Ÿ”ดRedshift
Materialized views with auto-refresh and incremental refresh for supported queries.
๐ŸฌMySQL
No built-in materialized views. Teams build summary tables with scheduled jobs or triggers.
๐Ÿ“Note
These are general ideas. Features differ a lot between products and versions, so check the current docs.
Mini case: an analytics dashboard
๐Ÿงพorders50M rows
โ‡ขโ‡ฃrefresh every 5 min
๐Ÿ“ฆdaily_sales40k rows, indexed
โ†’โ†“thousands of reads
๐Ÿ“ŠDashboard
๐Ÿ“งWeekly email
Thousands of dashboard views a day read the summary. The raw orders table is touched once every 5 minutes.

12Related Topics to Read Next

Denormalizationโ†’

A materialized view is managed denormalization.

Query Optimizationโ†’

Tune the query first. Materialize if it is still too heavy.

Indexingโ†’

Index the view like any table.

What is Caching?โ†’

A view is a cache inside the database.

Cache Invalidationโ†’

Refresh strategy is the same problem as invalidation.

Relational Databasesโ†’

Views, tables and SQL basics.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a query result stored as a table, refreshed on purpose.
  • โœ”Why: heavy joins and aggregates become fast reads.
  • โœ”Cost: stale data, storage, and refresh work.
  • โœ”Refresh: full, incremental, on commit, scheduled, or event-driven.
  • โœ”Pick by: how stale is OK? How big is the base table? How many reads?
  • โœ”Practice: index the view, refresh concurrently, show "updated at", alert on failure.
  • โœ”Not for: data that must be live and exact.
  • โœ”One line: โ€œDo the heavy query once, save the answer, and decide how old you let it get.โ€
โ† Previous
Denormalization
Next โ†’
Connection Pooling