Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 112/ 160
06. Database Design, Normalization & Semi-Structured SQL

Materialized Views & Concurrent Refresh Strategies

Cache expensive query results and refresh them without long locks.

IntermediateMaterialized View · REFRESH3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A materialized view is a saved answer to a slow question. It's fast to read, but you have to tell the database when to work out the answer again.

Think of it like…

A printed monthly report on a manager's desk: instant to read, but it shows numbers as of the day it was printed. To update it you print a new one, ideally without taking the old copy away while the printer runs.

Where you’ve seen it

A sales dashboard reads sales_daily_mv, which sums 200 million order lines by day and region. A cron job runs REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily_mv every hour, so the dashboard is at most an hour old and loads in milliseconds.

Words you’ll hear

Materialized view
A stored query result that can be indexed and must be refreshed.
REFRESH
Recomputes the whole result; blocks reads of the view while it runs.
CONCURRENTLY
Refreshes without blocking readers; needs a unique index; slower.
Staleness
How old the stored result can be, set by the refresh schedule.

Visual diagram

Loading interactive diagram

Theory & example queries

Creating and refreshing

CREATE MATERIALIZED VIEW sales_daily_mv AS SELECT … runs the query once and stores the rows. You can add indexes to it like a table. Its data stays fixed until a REFRESH, which in PostgreSQL re-runs the whole query from scratch, however little changed.

A plain REFRESH locks the view against reads for the whole recompute, so a dashboard would hang. REFRESH … CONCURRENTLY builds the new result separately, compares it with the old one and applies the differences, so readers keep seeing the old data until it's done. It needs a unique index on the view and takes longer.

Set up for concurrent refreshQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE MATERIALIZED VIEW sales_daily_mv AS2SELECT3  DAY,4  region,5  SUM(revenue) AS revenue6FROM7  order_lines8GROUP BY9  DAY,10  region;1112CREATE UNIQUE INDEX ON sales_daily_mv (DAY, region);1314REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily_mv;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command responses3 sample rows
Representative command responses
statementstatus
CREATE MATERIALIZED VIEWCREATE MATERIALIZED VIEW
CREATE UNIQUE INDEXCREATE INDEX
REFRESH MATERIALIZED VIEW CONCURRENTLYREFRESH MATERIALIZED VIEW

Note: PostgreSQL returns these command tags after a successful run. The refresh duration and materialized row count depend on the data and are not shown.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Add a unique index and refresh CONCURRENTLY for views people read during the day.

Choosing it, and its limits

Use a materialized view when the query is expensive, read often, and slightly stale data is acceptable. Schedule refreshes with cron, pg_cron or your orchestrator, at a frequency that matches how fresh users need it, and show "last updated" in the dashboard.

Because PostgreSQL always recomputes everything, a view over a huge table with frequent refreshes can become a cost of its own. Then a summary table updated incrementally (only new days) is better. Other systems go further: Oracle and SQL Server (indexed views) can maintain some views automatically, and warehouses like Snowflake and BigQuery offer automatically maintained materialized views.

Showing freshnessQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1INSERT INTO2  mv_refresh_log (view_name, refreshed_at)3VALUES4  ('sales_daily_mv', now());
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/4
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command response
INSERT 0 1

Note: This assumes one refresh-log row was inserted successfully; PostgreSQL command tags vary by client and dialect.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Store refresh times in a small table,

, after each refresh, and show it on the dashboard.

Key takeaway: Great for expensive, read-heavy, staleness-tolerant queries; switch to incremental tables when full refreshes get too costly.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Confirm the trade-off

Check that the query is slow, read frequently, and that users accept data that's minutes or hours old.

Focus at this step

slow + popular + staleness OK

What to watch at this step
Freshness
agree it upfront
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A materialized view stores the result of a query as real data, so reading it is as fast as reading a table, and you can index it. The catch: it doesn't update itself. In PostgreSQL you run REFRESH MATERIALIZED VIEW name to recompute it, or REFRESH MATERIALIZED VIEW CONCURRENTLY name to recompute it without blocking readers (which requires a unique index).

Why it matters: Dashboards that aggregate millions of rows can't run the full query on every page load. A materialized view trades freshness for speed. The interview questions are about that trade-off and about refreshing without taking the dashboard down.

When to reach for it

  • Dashboard and report aggregates
  • Precomputed lookups that join several large tables
  • Read-heavy analytics in PostgreSQL without a separate warehouse

When to avoid or be careful

  • Plain REFRESH on views read during business hours
  • Materialized views for data that must be real-time
  • Refreshing a huge view every minute when only today's data changes

View vs materialized view vs incremental summary table

Normal view
Best for: Always-current data from a reasonably fast query

Strengths: Never stale; nothing to refresh.

Watch out: Runs the full query on every read.

Materialized view
Best for: Expensive aggregates read often, staleness acceptable

Strengths: Fast indexed reads; simple to set up.

Watch out: Full recompute on each refresh; data as old as the last refresh.

Incrementally updated summary table
Best for: Huge sources where only recent data changes

Strengths: Updates only what changed; scales well.

Watch out: You write and maintain the update logic.

Interview signals & numbers to know

When this topic comes up

  • “The dashboard query takes 30 seconds”
  • “View vs materialized view”
  • “How do you refresh it without downtime?”
  • Precomputed aggregates
  • Staleness requirements

Benchmarks & rules of thumb

1 -
unique index needed for CONCURRENTLY
100% -
of the query re-run on each PostgreSQL refresh
0 -
automatic refreshes in core PostgreSQL

Common mistakes & follow-ups

Common interview mistakes

  • Running plain REFRESH during the day and freezing the dashboard until it finishes.
  • Trying REFRESH … CONCURRENTLY without a unique index and getting an error.
  • Forgetting to schedule refreshes, so the view silently shows weeks-old data.

Likely interviewer follow-ups

  • How does REFRESH MATERIALIZED VIEW CONCURRENTLY avoid blocking readers?
  • When would you choose a summary table over a materialized view?
  • How would you tell users how fresh the data is?
Interview tip: Frame it as speed versus freshness, then describe the refresh plan (CONCURRENTLY, unique index, schedule, monitoring). Operational detail is what makes the answer sound real.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Materialized Views & Concurrent Refresh Strategies with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Updatable Views & WITH CHECK OPTION
Next topic
Working with JSON & JSONB Data Types