Skip to main content
This can be used to create materialized views and sinks. See the practice in Sink data with upsert in Snowflake. The AS CHANGELOG clause adds two metadata columns:
  • changelog_op: the change type (1 = Insert, 2 = Delete, 3 = UpdateInsert, 4 = UpdateDelete)
  • _changelog_row_id: a monotonically increasing identifier that captures the order of the change.

Syntax

This uses common table expression (CTE) syntax within CREATE MATERIALIZED VIEW or CREATE SINK. It exposes changes from the source relation as rows with metadata columns. The optional KEY clause enables keyed changelogs; omit it to retain the existing per-change behavior.

Example

Create MV
Changelog operation
Query MV

Keyed changelogs

Use KEY (column_name [, ...]) to group change events by a business key. Each key column must be a distinct, visible column in the source relation. This key controls how changes are distributed and ordered; it does not declare a primary key or enforce uniqueness. Keyed changelogs buffer changes until each barrier. They compact changes using the upstream stream key together with the declared key, removing intermediate changes that cancel out within that interval. For rows sharing the declared key, removal events are emitted before addition events. This ensures that replacing a row leaves its addition as the latest event, even if the upstream insert arrives before the delete. Multiple upstream rows with the same declared key can still produce separate events. The following example tracks a business key, class_id, while the upstream materialized view groups by class_id, description, and free_usage. Changing a description replaces an upstream group but keeps the same business key.
The latest event for class 42 is the addition of the replacement row:
RW_IMPLICIT_FLUSH makes each data modification visible before the next statement in this example. After deleting class 42, the same query returns a latest event with __op = 2 for that class.