Materialized view (source code)

= Materialized view

A <materialized view> stores the result of a defining <database query>, allowing later queries to read the stored result. An ordinary <database view> retains the definition and evaluates it against the relevant underlying data when queried. A <materialized view> trades storage and maintenance work for potentially cheaper repeated reads; its freshness depends on when and how the result is maintained.<Materialized Views in the PostgreSQL documentation>[§39.3, opening comparison of CREATE MATERIALIZED VIEW and CREATE TABLE AS, persisted results and refresh]{ref}

Suppose an orders table contains totals 10 and 20 for one customer. A <materialized view> defined by `SELECT customer_id, SUM(total) AS total FROM orders GROUP BY customer_id` stores 30 for that customer. Inserting a third order worth 7 changes the underlying sum to 37. In PostgreSQL, the previously stored 30 remains until a refresh replaces the result, for example with `REFRESH MATERIALIZED VIEW customer_totals;`. The stored answer can therefore be internally consistent yet out of date.

A dashboard that tolerates nightly updates can benefit from this arrangement, especially when the defining <database query> combines many rows. An application requiring the latest committed totals needs a suitable maintenance policy and <database transaction> semantics. The term <materialized view> alone does not promise automatic updates or an always faster query.<Materialized Views in the PostgreSQL documentation>[§39.3, sales_summary example and nightly REFRESH MATERIALIZED VIEW]{ref}