SQL · Queries that survive scale
What is a materialized view and how do you refresh it?
Short answer
A materialized view stores the result of a query on disk. Reads are fast, but the data is only as fresh as the last refresh, which must be scheduled or triggered.
Unlike a regular view, a materialized view persists rows. That makes it useful for expensive aggregations and dashboards where slightly stale data is acceptable. The trade-off is refresh cost and staleness.
CREATE MATERIALIZED VIEW monthly_revenue AS
SELECT date_trunc('month', created_at) AS month,
SUM(total_cents) AS revenue_cents
FROM orders
WHERE status = 'paid'
GROUP BY 1;
CREATE UNIQUE INDEX ON monthly_revenue (month);Refresh strategies
- REFRESH MATERIALIZED VIEW rebuilds the whole result and blocks reads by default
- REFRESH MATERIALIZED VIEW CONCURRENTLY can keep reads available but requires a unique index
- Schedule refreshes after ETL or on a cadence that matches the freshness requirement
- Incremental maintenance often needs a separate summary table rather than a full refresh
- Views can be indexed like tables, which helps large analytical queries
- Monitor refresh duration as data grows; a full rebuild can become the bottleneck
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_revenue;If the application cannot tolerate stale dashboards, a materialized view is the wrong tool. If it can tolerate minutes or hours of delay, a materialized view can remove a large repeated aggregation from the request path.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a view and a materialized view?
- 2What does REFRESH MATERIALIZED VIEW CONCURRENTLY require?
- 3How do you decide on a refresh cadence?
- 4When would a summary table be better?
Say it in the interview
A materialized view stores the result of a query, so reads avoid recomputing an expensive aggregation. The cost is staleness and refresh work. In PostgreSQL, a concurrent refresh needs a unique index and still does more work than a plain refresh. I use materialized views for dashboards and reports with a known freshness tolerance, not for data that must be current on every read.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live SQL mock interview and get scored feedback on depth, clarity and confidence.