How-To Guide

How to Implement Incremental Materialized Views

Keep a materialized aggregate fresh incrementally: track changed keys, refresh only affected rows, and reconcile with a periodic full refresh.

On this page

  1. Introduction
  2. Store the aggregate in a table you can upsert
  3. Identify the incremental delta
  4. Handle deletes and empty groups
  5. Advance the watermark and reconcile
  6. Test the delta path
  7. Common pitfalls
  8. Conclusion

Introduction

A materialized view caches the result of an expensive query so reads are fast, at the cost of staleness and refresh work. The built-in refresh recomputes the whole result, which is fine for small data and painful for large: a single row changing forces the entire aggregate to be recomputed. Incremental refresh trades that for a smaller, targeted computation: find the keys whose source rows changed and recompute only those.

This tutorial implements an incremental aggregate that keeps a per-key summary fresh by recomputing only affected keys, records a watermark, and reconciles with a periodic full recompute. The examples use PostgreSQL, but the pattern of a delta plus an upsert applies to any database.

Store the aggregate in a table you can upsert

A materialized view can only be refreshed wholesale, so an incremental design stores the result in an ordinary table with a primary key on the group. That key lets each affected group be upserted or replaced individually. Copy the query’s output shape into a table, add the group key as the primary key, and treat the table as a cache maintained by your refresh job.

Add a column recording the watermark, the point in the source the aggregate reflects. The watermark lets the next run know where the last refresh stopped, so the delta is everything after it. Store the watermark per aggregate table so several incremental views can advance independently, and update the watermark in the same transaction as the recompute so a crash cannot advance it past what was applied.

CREATE TABLE customer_revenue (
  customer_id  bigint PRIMARY KEY,
  revenue      numeric NOT NULL,
  order_count  bigint NOT NULL,
  updated_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE refresh_watermark (
  aggregate   text PRIMARY KEY,
  applied_to  timestamptz NOT NULL
);

Identify the incremental delta

The delta is the set of source rows that changed since the watermark. A change log table that records each insert, update, and delete gives the exact delta including deletes. An updated_at timestamp on the source is simpler but misses hard deletes, because a deleted row has no timestamp to advance. Choose the change log when deletes matter, and the timestamp when only inserts and updates occur.

From the delta, derive the set of group keys to recompute. Group the changed rows by their group key and collect the distinct keys. Then recompute only those keys by scanning the source filtered to those keys, not the whole table. This is the core of incremental refresh: the work is proportional to the keys that changed, not to the total number of groups.

WITH changed AS (
  SELECT DISTINCT customer_id
  FROM orders
  WHERE updated_at > (SELECT applied_to FROM refresh_watermark WHERE aggregate = 'customer_revenue')
),
recomputed AS (
  SELECT o.customer_id, sum(o.total) AS revenue, count(*) AS order_count
  FROM orders o
  JOIN changed c ON c.customer_id = o.customer_id
  GROUP BY o.customer_id
)
INSERT INTO customer_revenue (customer_id, revenue, order_count, updated_at)
SELECT customer_id, revenue, order_count, now() FROM recomputed
ON CONFLICT (customer_id) DO UPDATE
  SET revenue = EXCLUDED.revenue,
      order_count = EXCLUDED.order_count,
      updated_at = now();

Handle deletes and empty groups

If a group’s source rows are all deleted, recomputing the group produces no row, and a plain upsert leaves the stale summary in place. Delete the affected keys first, or delete keys that are in the changed set but absent from the recomputed result, so a group with no remaining source rows disappears from the summary. The change log makes this precise: a delete event names the key to remove.

For a group that still has rows but lost some, the recompute recalculates from the surviving rows, so the summary naturally shrinks. The trap is only the fully-emptied group, where the recompute yields nothing and the upsert has nothing to update. Handle it explicitly by deleting keys in the changed set that the recompute did not produce.

-- remove summaries for groups that no longer have source rows
DELETE FROM customer_revenue cr
WHERE cr.customer_id IN (
  SELECT DISTINCT customer_id FROM order_change_log
  WHERE changed_at > (SELECT applied_to FROM refresh_watermark WHERE aggregate='customer_revenue')
)
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = cr.customer_id);

Advance the watermark and reconcile

Advance the watermark to the maximum changed timestamp processed, in the same transaction as the recompute. If the watermark moves without the recompute committing, the next run skips the delta and the summary drifts. If the recompute commits without the watermark, the next run reprocesses the same delta, which is idempotent if the recompute is a full recompute of those keys, so a repeated run converges.

Incremental refresh can drift from the truth through a missed delta or a bug in the key derivation. A periodic full recompute, run less often, catches that. Compare the full result against the incremental result and alert on any difference; then replace the incremental table with the full one to resynchronize. The full refresh is the ground truth that keeps the fast path honest.

-- periodic reconciliation: find keys where the fast path disagrees with the truth
WITH truth AS (
  SELECT customer_id, sum(total) AS revenue FROM orders GROUP BY customer_id
)
SELECT t.customer_id, t.revenue AS truth_revenue, cr.revenue AS cached_revenue
FROM truth t
FULL JOIN customer_revenue cr USING (customer_id)
WHERE t.revenue IS DISTINCT FROM cr.revenue;

Test the delta path

Test that inserting a new order for one customer updates only that customer’s summary and leaves others untouched. Test that deleting a customer’s last order removes the summary row. Test that running the refresh twice with no intervening change is a no-op. Test that a full recompute after a series of incremental updates matches the incremental result, which proves the delta path did not drift.

psql -d app <<'SQL'
INSERT INTO orders (customer_id, total) VALUES (1, 50.00);
SELECT revenue FROM customer_revenue WHERE customer_id = 1;  -- new value
SELECT updated_at FROM refresh_watermark WHERE aggregate='customer_revenue'; -- advanced
SELECT count(*) FROM customer_revenue WHERE customer_id = 2 AND updated_at > now() - interval '1 min'; -- 0, untouched
SQL

Common pitfalls

Using a timestamp delta and missing hard deletes, forgetting to delete summaries for emptied groups, advancing the watermark before the recompute commits, never reconciling with a full refresh so drift goes unnoticed, and recomputing the whole source instead of only the changed keys are the recurring mistakes. A change log for deletes, explicit removal of empty groups, transactional watermark, periodic reconciliation, and key-scoped recompute address them.

Conclusion

Incremental materialized views replace a full refresh with a delta. Store the aggregate in an upsertable table, derive the changed keys, recompute only those, remove emptied groups, advance the watermark transactionally, and reconcile with a periodic full recompute. Self-check by asserting only the changed key updates and that a full recompute matches the incremental result. The fast path stays fast and, through reconciliation, stays correct.

Sources: PostgreSQL: Materialized views, PostgreSQL: REFRESH MATERIALIZED VIEW, PostgreSQL: ON CONFLICT (upsert).

FAQ

Why not just REFRESH MATERIALIZED VIEW every time?
A full refresh recomputes the entire result, which is expensive on large data and, without CONCURRENTLY, locks the view. Incremental refresh recomputes only the groups whose source rows changed, so a small write costs a small refresh.
How do I know which keys changed?
Track a change log or an updated_at timestamp on the source table and record the last-applied watermark. Everything with a timestamp after the watermark is the delta. A change log gives exact deletes and updates; a timestamp is simpler but can miss hard deletes.

Related Examples