Careeroza
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
| View | Materialized view | |
|---|---|---|
| Stores | only the query | query + result data |
| Freshness | always current | as of last refresh |
| Read speed | same as running the query | fast (precomputed) |
| Typical use | simplify, secure | dashboards, heavy aggregates |