Precompute and store a query's result shape ahead of time, refreshed as source data changes, instead of recomputing it on every read.
A dashboard showing "total sales per region, joined with product category" might require aggregating across millions of order rows. Running that full aggregation query every time someone loads the dashboard is wasteful when the underlying data only changes a few times a minute.
Instead of querying source tables directly at read time, a materialized view stores the precomputed result shape. It's refreshed periodically, or updated incrementally as source data changes — reads then hit the cheap, pre-shaped view instead of the expensive source query.
`refreshSalesByRegion` does the expensive aggregation once; `getSalesByRegion` afterward is a cheap lookup, no matter how many times it's called.
const orders = [
{ region: "west", amount: 100 }, { region: "west", amount: 50 },
{ region: "east", amount: 75 },
];
let salesByRegionView = null; // the materialized view
function refreshSalesByRegion() {
console.log("recomputing aggregation over all orders...");
const totals = {};
for (const order of orders) {
totals[order.region] = (totals[order.region] ?? 0) + order.amount;
}
salesByRegionView = totals;
}
function getSalesByRegion() {
return salesByRegionView; // cheap read, no recomputation
}
refreshSalesByRegion(); // run on a schedule, or triggered when orders change
console.log(getSalesByRegion());
console.log(getSalesByRegion()); // second call: no recomputation at all