Materialized views, refresh and stale reports
Overview
A materialized view stores the result of a query for later reads. This trades freshness and maintenance cost for potential read savings. PostgreSQL supports materialized views and refresh commands. SQLite does not provide this native object; an ordinary summary table maintained by an explicit transaction illustrates stored-result staleness, not native materialization semantics.
First example
BEGIN;UPDATE vw_product SET price=150 WHERE id=1;SELECT l.category,l.total,s.total FROM vw_live l JOIN vw_summary s ON l.category=s.category ORDER BY l.category;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "office", 350, 300 ]]How it works
The first example changes an active product price and compares the live aggregate with the unchanged stored total. The second replaces summary rows in one transaction and checks the refreshed result. A failure before commit must roll back the replacement. PostgreSQL REFRESH MATERIALIZED VIEW recomputes stored results; CONCURRENTLY requires an already populated view and a qualifying unique index covering all rows with ordinary columns. PostgreSQL 17 requires MAINTAIN privilege. Concurrent refresh allows readers but is not incremental refresh and does not promise zero waits. Evaluate freshness requirements, query plans, indexes and refresh cost. SQL Server indexed views are a distinct engine-specific design; do not treat them as identical.
Practical example
BEGIN;UPDATE vw_product SET price=150 WHERE id=1;DELETE FROM vw_summary;INSERT INTO vw_summary SELECT category,total FROM vw_live;SELECT category,total FROM vw_summary ORDER BY category;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ "office", 350 ]]Practice and mistakes
Practice: activate product 3, compare the live category totals to the summary table, rebuild the summary inside a transaction and verify equality in both directions. Hint 1: use the same GROUP BY definition. Hint 2: compare with EXCEPT in both directions. Expect a new category row. Mistake: treating cached aggregates as always current or assuming refresh improves performance without measuring.