Materialized view

On this page 7

A materialized view is a database object that stores the result of a query physically, as if it were a table, and keeps that result up to date through a refresh mechanism, so that repeated queries read precomputed data instead of recalculating it. In database performance work, it is one of the most effective tools for accelerating expensive aggregations and joins that are read far more often than their source data changes.

The price is staleness and maintenance cost. Between refreshes the stored result can lag behind the base tables, and every refresh consumes processing time, input and output and storage, which makes the refresh strategy the central design decision.

How a materialized view stores and refreshes results

A materialized view is defined by a query, just like an ordinary view. The difference is that the database executes the query once and saves the rows, often in a structure that can be indexed. Later queries against the view read these rows directly, avoiding the original joins, filters and aggregations.

Keeping the data current is the job of the refresh. A complete refresh reruns the defining query and replaces the contents. An incremental or fast refresh applies only the changes made to the base tables since the last refresh, usually tracked in change logs. Incremental maintenance is far cheaper for large views, but it restricts which queries are supported.

StrategyHow it worksFreshnessCost profile
Complete refresh on demandRerun the query when triggeredAs fresh as the last runHigh per refresh, zero between
Scheduled refreshComplete or incremental at fixed intervalsMinutes to hours oldPredictable batch load
Incremental refreshApply logged base-table changesClose to currentLow per refresh, logging overhead on writes
Refresh on commitUpdate the view in each writing transactionAlways currentSlows every write to the base tables
Refresh strategies

Support in major database systems

Implementations differ widely, and the name alone says little about behavior. Some systems offer full manual control, others maintain the view automatically, and some call the feature by another name.

SystemRefresh modelNotable features
PostgreSQLManual complete refreshConcurrent refresh needs a unique index on the view
Oracle DatabaseComplete, fast, on demand or on commitMaterialized view logs, automatic query rewrite
SQL ServerIndexed views maintained synchronouslyStrict rules on deterministic expressions
Cloud data warehousesMostly automatic background maintenanceRestrictions on joins and functions
Streaming databasesContinuous incremental maintenanceResults updated as events arrive
Materialized views across systems

In PostgreSQL, a plain refresh takes a lock that blocks reads of the view for its duration, while the concurrent variant keeps the view readable at the cost of a slower, difference-based update. Oracle’s query rewrite can transparently redirect a query against base tables to a matching materialized view, so applications benefit without being changed.

Several techniques trade freshness or storage for read speed, and the right choice depends on where the result is stored, who maintains it and how stale it may become. The comparison below places the materialized view among its closest alternatives.

TechniqueStored resultMaintained byMain trade-off
Ordinary viewNo, query runs each timeNot applicableAlways fresh, no speedup
Materialized viewYes, in the databaseDatabase refresh mechanismSpeed versus staleness and refresh cost
Summary tableYes, in the databaseApplication or batch jobsFull control, more custom code
Query cacheYes, exact result setsCache layer, invalidated on changeHelps only identical queries
Covering indexSelected columns onlyDatabase on every writeNo precomputed joins or aggregates
Materialized view and alternatives

Materialized views are also a standard tool for denormalization without application code. Instead of duplicating data manually across tables, a team defines the denormalized shape as a view and lets the database handle consistency within the chosen refresh window.

Designing an effective materialized view

A materialized view pays off when the read-to-write ratio is high and the defining query is expensive. Typical candidates are dashboards, reporting aggregates, search listings built from several joined tables and precomputed rollups in analytical schemas.

  • Agree on acceptable staleness with the consumers first, then choose the refresh method and frequency to match it.
  • Index the view for the queries that read it, exactly as for a table.
  • Aggregate to the coarsest useful grain, such as daily totals instead of individual events, to keep the view small.
  • Schedule refreshes away from peak load and monitor their duration as data grows.
  • Layer views carefully, refreshing dependent views in the correct order.

Refresh duration should be measured, not assumed. A view that refreshes in two minutes on a test dataset may need far longer in production, and if a complete refresh takes longer than the scheduled interval, refreshes begin to overlap and the view never becomes current.

Limitations and common mistakes

The most dangerous problem is silent staleness: users read the view as if it were live data and make decisions on numbers that are hours old. Exposing a last-refreshed timestamp alongside the data is a simple and effective safeguard.

PitfallSymptomRemedy
Refresh on commit for busy tablesWrite latency increases sharplySwitch to scheduled or incremental refresh
Blocking refreshReports wait or time out during refreshUse concurrent refresh or swap tables
View used for volatile dataResults are always outdatedUse indexes or query tuning instead
Unsupported query for fast refreshSilent fallback to complete refreshSimplify the query or add change logs
Pitfalls and remedies

In simple terms

Imagine a store manager who wants the day’s sales total. Adding up every receipt each time someone asks would take ages. Instead, an assistant writes the total on a whiteboard every hour, and anyone can read it instantly.

A materialized view is that whiteboard inside a database. It answers questions quickly because the hard work was done in advance, but the number is only as current as the last update, so someone must decide how often to rewrite it.

A practical example

A subscription business runs a management dashboard showing revenue by region, product and month. The underlying query joins invoices, customers and products across several hundred million rows and takes over a minute, so the dashboard is slow and puts heavy load on the primary database.

The data team creates a materialized view holding monthly revenue per region and product, adds an index on region and month, and refreshes it every 30 minutes with a concurrent refresh. The dashboard now loads in under a second, displays the time of the last refresh, and database load during business hours drops considerably, since the expensive query runs only twice an hour.