Incremental Views
Derived numbers the database keeps current
What happens
Three rows commit in one transaction
The view is brought up to date from the change alone, inside that commit
The read is already current; nothing refreshed it in between
- 1
Declare what the number is
A
deferred viewis a query you declare once. From then on the database maintains it for you: when a write commits, the view is brought up to date incrementally, using only what changed rather than running the whole query again.Nothing recomputes it on a timer, and nothing has to remember to invalidate a cache key. The work is proportional to the write, not to the size of the table.
Declare what the number iscreate namespace ex_views; create table ex_views::orders { id: int4, region: utf8, total: float8 }; create deferred view ex_views::revenue { region: utf8, revenue: float8 } as { from ex_views::orders aggregate { revenue: math::sum(total) } by { region } } - 2
Write to the source table only
Nothing in this statement mentions
ex_views::revenue. There is no second write, no queue message, and no cache key to bust.Write to the source table onlyinsert ex_views::orders [ { id: 1, region: "eu", total: 120.0 }, { id: 2, region: "us", total: 80.0 }, { id: 3, region: "eu", total: 45.5 } ] - 3
Read the view
The view has already caught up. No cron job, worker or cache invalidation ran between the insert above and this read.
No refresh, no worker, no cronfrom ex_views::revenue sort { revenue: desc } What you now have
A number that is always current, maintained by the database from the writes themselves. There is no job to schedule, no cache to invalidate, and no window where the view disagrees with the table it is derived from.
