A materialized view is a table you did not write
A view is a saved query that executes every time you touch it. A materialized view is the result of that query, stored on disk with its own indexes, statistics, and storage cost. The trade is immediate: reads get faster because the aggregation already happened, and writes get slower because someone must eventually recompute the result. Every design decision that follows is a negotiation over who pays and when.
The second consequence is that materialization introduces staleness, which is a semantic change rather than a performance one. A view never lies about the current data; a materialized view reports a moment in the past and does so confidently. Consumers must therefore know the freshness of what they are reading, which means staleness has to be observable â a timestamp column, a metric, an alert â rather than assumed.
By the end of this lesson you should be able to pick a refresh strategy from write volume and freshness requirements, verify that a query is actually being rewritten onto a rollup, and measure staleness in terms a stakeholder will accept.
Refresh strategies and what each guarantees
Refresh strategy determines the cost distribution across the day and the guarantees a reader can rely on. The choice is driven by how often the base tables change and how much downtime a full rebuild would cost.
| Strategy | When it runs | Cost | Freshness | Requirement |
|---|---|---|---|---|
| Full refresh | On demand or schedule | Rebuild everything | Up to one cycle old | None |
| Fast / incremental | On commit or schedule | Only changed rows | Near real time | Change tracking or MV log |
| Concurrent refresh | Continuous | Overlapping builds | Fresh during build | Snapshot isolation on base |
| Manual | Operator-triggered | Whenever run | Until someone runs it | Runbook and discipline |
| Deferred to query | First query after change | Paid by the reader | Fresh at read time | Rewrite support |
Full refresh is the honest default: simple, always correct, and fine until the table grows large enough that a rebuild takes longer than the freshness window. Fast refresh flips the cost to every write, because the engine must record and apply deltas â and if the view contains a DISTINCT or a non-incremental aggregate, fast refresh may be impossible or slower than a full rebuild. Concurrent refresh is the answer when you cannot afford a rebuild window, at the cost of maintaining two versions while the new one builds.
Building and refreshing on a schedule
The operational core is a refresh that fits inside the freshness window, with a staleness signal that fires before consumers notice. Scheduling the refresh is easy; making its duration and lag visible is what makes it production-grade.
-- Definition and refresh control
CREATE MATERIALIZED VIEW mv_daily_revenue
AS
SELECT order_date,
region,
COUNT(*) AS orders,
SUM(amount) AS revenue,
COUNT(DISTINCT customer_id) AS buyers
FROM orders
WHERE status = 'completed'
GROUP BY order_date, region;
-- Unique index enables incremental maintenance in engines that support it
CREATE UNIQUE INDEX ux_mv_daily_revenue
ON mv_daily_revenue (order_date, region);
-- Freshness signal consumers and alerting can read directly
COMMENT ON MATERIALIZED VIEW mv_daily_revenue IS 'grain: order_date, region';
-- Scheduled refresh with a measured lag
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_revenue;
-- Observability: is the rollup keeping up?
SELECT now() - max(order_date) AS data_age,
pg_stat_get_last_autovacuum_time('mv_daily_revenue'::regclass) AS last_vacuum
FROM mv_daily_revenue;
The unique index is not cosmetic. Several engines can only perform incremental maintenance when the result has a key they can upsert on; without it, every refresh is a full rebuild regardless of what the schedule says. CONCURRENTLY lets readers keep using the old version while the new one builds, which is what makes a twice-hourly refresh tolerable on a table that never stops receiving writes.
Automatic query rewriting: the quiet saver
The most valuable feature in this area is the optimiser rewriting a query you did not change so it runs against the rollup instead of the raw tables. When it works, nobody has to remember which materialized view to query; when it silently stops working, a schema change quietly doubles a nightly job's runtime.
-- Oracle: the view is eligible for rewrite and carries query text
CREATE MATERIALIZED VIEW mv_region_rollup
REFRESH COMPLETE ON SCHEDULE EVERY 1 HOUR
ENABLE QUERY REWRITE
AS
SELECT r.region_name,
SUM(f.amount) AS total_amount,
COUNT(*) AS fact_count
FROM fact_sales f
JOIN dim_region r ON r.region_id = f.region_id
GROUP BY r.region_name;
-- Prove the rewrite happened: the plan references the rollup
EXPLAIN PLAN FOR
SELECT region_name, SUM(total_amount)
FROM mv_region_rollup
GROUP BY region_name;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
-- Look for: mat_view_rewrite mv_region_rollup
-- PostgreSQL: make the planner consider the alternative explicitly
SET enable_seqscan = off;
EXPLAIN (ANALYZE)
SELECT region_name, SUM(total_amount)
FROM mv_region_rollup
GROUP BY region_name;
Verification belongs in your change process. Any time someone alters a base table, adds a column, or changes a constraint, re-run the plans for the queries that depended on rewriting. The failure mode is invisible: no error, no warning, just a plan that now scans the fact table and a bill that arrives a week later.
Rewriting has limits worth knowing. Queries with functions the rewrite cannot match, predicates referencing columns absent from the view, or aggregates that cannot be derived from the stored ones will not rewrite. Matching is structural, so even a semantically identical query written differently â reordered joins, an equivalent date expression â may fail to match. Keep a canonical query template for the hot paths and test against it.
Incremental maintenance in practice
Fast refresh requires the engine to know what changed. In warehouse engines this is often automatic; in servers it usually means a materialized view log recording row identifiers per base table, which the refresh uses to apply a delta rather than a rebuild.
-- Change-tracking log so refresh can apply deltas
CREATE MATERIALIZED VIEW LOG ON orders
WITH ROWID, SEQUENCE (order_date, region, amount, status)
INCLUDING NEW VALUES;
-- Fast refresh: only rows touched since the last run
REFRESH MATERIALIZED VIEW mv_daily_revenue FAST;
-- Guard: report whether the refresh actually took the fast path
SELECT refresh_mode, staleness
FROM user_mviews
WHERE mview_name = 'MV_DAILY_REVENUE';
Reading the recorded refresh mode back from the catalogue is the check that matters. A view configured for fast refresh that silently falls back to complete every night is a slow-motion incident: nothing fails, but the schedule eventually cannot keep up with the data volume. Track refresh duration as a metric too; a rising trend usually means either growing base data or a missing incremental capability.
Measuring staleness consumers accept
"Approximately fresh" is not a specification. Staleness should be expressed as a service level: the rollup is no more than fifteen minutes behind the base tables on 99 percent of checks, measured by comparing the newest base timestamp against the newest rollup timestamp.
-- Staleness SLO measurement, runnable as a monitoring query
WITH base AS (
SELECT max(updated_at) AS newest FROM orders
),
rollup AS (
SELECT max(refreshed_at) AS newest FROM mv_daily_revenue
)
SELECT now() - base.newest AS base_age,
now() - rollup.newest AS rollup_age,
base.newest - rollup.newest AS lag_seconds,
CASE WHEN base.newest - rollup.newest >= INTERVAL '15 minutes'
THEN 'within_slo' ELSE 'breach' END AS status
FROM base, rollup;
Attach the result to an alert and to the documentation consumers read. When a refresh is delayed, they should learn about it from the same dashboard you do, not from a report that quietly used yesterday's totals. And when a stakeholder asks whether they can trust a number, the answer becomes a timestamp rather than a reassurance.
đĄRefresh before you optimize
If a job is slow and reads pre-aggregated tables, check the refresh lag first. Half of "the query got slower" reports turn out to be a rollup that stopped refreshing and a query that fell back to the raw tables.
Common Mistakes
Assuming a materialized view is always current
Fix: Expose refresh timestamps, measure lag against an SLO, and alert on breach
Configuring fast refresh and never verifying the engine took that path
Fix: Read the recorded refresh mode after each run and alert on unexpected complete refreshes
Trusting automatic rewrite after schema changes
Fix: Re-run EXPLAIN on dependent queries whenever a base table or constraint changes
Building rollups for queries nobody runs
Fix: Start from measured query frequency and cost; a rollup with no reader is pure write tax
Best Practices
- Choose the refresh strategy from write volume and the freshness contract, not from default settings
- Index the materialized view the way you would index a table written by hand
- Measure refresh duration and lag as metrics with owners
- Keep a canonical query template so rewrite matching stays deterministic
- Document the grain of every rollup in a comment so joins cannot silently multiply rows
Interview Questions
Q1: View versus materialized view?
A view is a saved query executed on access; a materialized view stores the computed result, trading freshness for read speed.
Q2: Why might fast refresh be unavailable?
The query may not be incrementally maintainable â non-additive aggregates such as COUNT DISTINCT â or change tracking may not be configured on the base tables.
Q3: How do you confirm a query used a materialized view?
Inspect the execution plan for a rewrite or mat_view access path, and keep that check in your change process.
Q4: How should staleness be communicated?
As a measured lag against a stated service level, surfaced in metadata and alerting rather than assumed.
Key Takeaways
- Materialization moves cost from read to write and introduces a semantic change: staleness
- Refresh strategy should follow write volume and the freshness contract
- Incremental maintenance needs a key and change tracking, and the chosen path must be verified
- Automatic rewrite is invisible until it stops, so plan checks belong in review
- Measure lag against an SLO and let consumers see freshness next to the number