Materialized Views

Stored Results

A materialized view stores the result of its query on disk, like a table. Reads are very fast, but the data is only as fresh as the last refresh.

-- PostgreSQL
CREATE MATERIALIZED VIEW MonthlySales AS
SELECT date_trunc('month', OrderDate) AS Month, SUM(Amount) AS Revenue
FROM Orders GROUP BY 1;

REFRESH MATERIALIZED VIEW MonthlySales;

-- Oracle
CREATE MATERIALIZED VIEW MonthlySales REFRESH COMPLETE ON DEMAND AS SELECT ...;

-- SQL Server: "indexed views"
CREATE VIEW dbo.MonthlySales WITH SCHEMABINDING AS SELECT ...;
CREATE UNIQUE CLUSTERED INDEX IX_MonthlySales ON dbo.MonthlySales(Month);

View vs Materialized View

ViewMaterialized view
Storesonly the queryquery + result data
Freshnessalways currentas of last refresh
Read speedsame as running the queryfast (precomputed)
Typical usesimplify, securedashboards, heavy aggregates