Explain the concept of 'Materialized Views' and their advantages.
Instruction: Define materialized views, how they differ from standard views, and when to use them.
Updated
Official answer
A materialized view persists a query result. Reads can avoid repeating an expensive computation, in exchange for storage, refresh cost and staleness. An ordinary view stores its definition and reads underlying data through that query instead.
Assume PostgreSQL sales(product_id integer, amount numeric):
CREATE MATERIALIZED VIEW product_totals AS
SELECT product_id, SUM(amount) AS total
FROM sales
GROUP BY product_id;
REFRESH MATERIALIZED VIEW product_totals;
The initial creation populates this view. Later source-table changes are not automatically reflected; refresh replaces the stored result according to its snapshot. Define a freshness target, refresh ownership, failure monitoring and resource budget.
Ordinary refresh can block readers. PostgreSQL REFRESH MATERIALIZED VIEW CONCURRENTLY has requirements, including an already populated view and a qualifying UNIQUE index using columns and covering all rows; it is not a free incremental-refresh switch. Only one refresh per materialized view runs at a time. Test the actual query and workload rather than assuming materialization improves every report.