Memra

Materialized views

◈ 2 cards

Cache an expensive query result on disk.

A cached view

A plain view recomputes every time. A materialized view stores the result, trading freshness for speed — ideal for expensive aggregations read far more often than the data changes:

CREATE MATERIALIZED VIEW genre_counts AS
  SELECT genre, count(*) AS n FROM books GROUP BY genre;

It won't update on its own — you refresh it when you want new numbers:

REFRESH MATERIALIZED VIEW genre_counts;
VIEWMATERIALIZED VIEWstored?nothing storedresult rows on diskfreshnessalways liveas of the last REFRESHread costruns the query each timealready computedupkeepnoneREFRESH MATERIALIZED VIEWFreshness traded for speed — never by accident.
One trade, stated four ways: you buy read speed with staleness and an upkeep job. Reach for a materialized view when the query is expensive and the data changes far less often than it is read — and when someone owns the REFRESH.
NORMAL ~/memra/learn/postgresql/materialized-views utf-8 LF