Menu

Databricks course · Lesson 11 of 13

Declarative Pipelines in Depth: AUTO CDC, SCD Type 2 and Data Quality

Use Lakeflow declarative pipelines for change data capture: AUTO CDC for SCD Type 1 and 2, snapshots, expectations with quarantine tables, the event log, and when to choose plain streaming.

  • Advanced
  • 8 min read
  • Updated Nov 2026
On this page
  1. Why CDC needs special handling
  2. AUTO CDC for SCD Type 1
  3. AUTO CDC for SCD Type 2
  4. Sources without a change feed: AUTO CDC FROM SNAPSHOT
  5. Data quality: warn, drop, fail or quarantine
  6. Streaming table or materialized view?
  7. Declarative pipelines or Structured Streaming?
  8. Reading the event log
  9. Operating pipelines
  10. Common mistakes
  11. Interview angle
  12. Key takeaway

The Auto Loader and declarative pipelines lesson introduced streaming tables, materialized views and expectations. This lesson covers the parts that come up in production and in the Professional exam. It shows how to turn a change feed into slowly changing dimensions with AUTO CDC, handle sources that only give you snapshots, and keep bad records instead of losing them. It ends with the pipeline event log and when a declarative pipeline is the wrong tool.

Why CDC needs special handling

A change data capture (CDC) feed from a database is a stream of inserts, updates and deletes, each with a key and an ordering column such as a log sequence number or a timestamp. Applying it to a Delta table by hand means writing a MERGE in foreachBatch that:

  • deduplicates several changes to the same key in one batch,
  • applies them in sequence order even when they arrive out of order,
  • turns delete events into deletes, and
  • for SCD Type 2, closes the previous version of a row and opens a new one.

That logic is easy to get subtly wrong. AUTO CDC (formerly APPLY CHANGES, which still works with the same syntax) does it for you.

AUTO CDC for SCD Type 1

Suppose a CDC feed lands in a bronze streaming table customers_cdc with columns customer_id, name, city, op (INSERT, UPDATE or DELETE) and change_ts. An SCD Type 1 target keeps only the current row per customer:

CREATE OR REFRESH STREAMING TABLE customers_current;

CREATE FLOW customers_current_flow AS AUTO CDC INTO customers_current
FROM STREAM(customers_cdc)
KEYS (customer_id)
APPLY AS DELETE WHEN op = 'DELETE'
SEQUENCE BY change_ts
COLUMNS * EXCEPT (op, change_ts)
STORED AS SCD TYPE 1;
  • KEYS identifies the row; it can be several columns.
  • SEQUENCE BY gives the logical order. If an older change arrives after a newer one, the older one does not overwrite the newer. Use a STRUCT of several columns when one column can tie.
  • APPLY AS DELETE WHEN turns matching events into deletes.
  • COLUMNS * EXCEPT keeps CDC bookkeeping columns out of the target.

Two optional clauses matter for real feeds. IGNORE NULL UPDATES keeps the existing value when an update carries a null, which suits sources that send only changed columns. APPLY AS TRUNCATE WHEN empties the target on a truncate event, and is supported only for SCD Type 1.

AUTO CDC for SCD Type 2

Change STORED AS SCD TYPE 2 and the target keeps every version, with __START_AT and __END_AT columns taken from the sequence column. The current row has __END_AT null.

CREATE OR REFRESH STREAMING TABLE customers_history;

CREATE FLOW customers_history_flow AS AUTO CDC INTO customers_history
FROM STREAM(customers_cdc)
KEYS (customer_id)
APPLY AS DELETE WHEN op = 'DELETE'
SEQUENCE BY change_ts
COLUMNS * EXCEPT (op, change_ts)
STORED AS SCD TYPE 2
TRACK HISTORY ON * EXCEPT (name);

TRACK HISTORY ON limits which columns create a new version. Here a change of city opens a new version, while a corrected spelling of the name updates the current version in place. Without it, every column change creates a version, which can bloat a dimension that receives noisy updates.

The same flow in Python:

from pyspark import pipelines as dp
from pyspark.sql import functions as F

dp.create_streaming_table("customers_history")

dp.create_auto_cdc_flow(
    target="customers_history",
    source="customers_cdc",
    keys=["customer_id"],
    sequence_by=F.col("change_ts"),
    apply_as_deletes=F.expr("op = 'DELETE'"),
    except_column_list=["op", "change_ts"],
    stored_as_scd_type=2,
    track_history_except_column_list=["name"],
)

Reading the current customers from an SCD Type 2 table is then a filter:

SELECT customer_id, name, city
FROM customers_history
WHERE __END_AT IS NULL;

For deletes in SCD Type 2, the pipeline keeps a tombstone for a while so that late, out-of-order events are still applied correctly, and exposes the table through a view that hides the tombstones.

Sources without a change feed: AUTO CDC FROM SNAPSHOT

Some systems can only give you a full copy of a table each day. AUTO CDC FROM SNAPSHOT compares consecutive snapshots, works out the inserts, updates and deletes, and applies them as SCD Type 1 or Type 2. Use it instead of hand-written “compare yesterday with today” jobs. For SCD Type 1 targets it can be combined with an AUTO CDC flow: periodic snapshots act as the authority and the change feed fills the gaps between them.

Data quality: warn, drop, fail or quarantine

Expectations attach a rule to a dataset and record pass and fail counts on every update. Choose the action per rule:

Action SQL Python Use when
Warn (keep the row) EXPECT (cond) @dp.expect You want visibility but the row is still usable
Drop the row ... ON VIOLATION DROP ROW @dp.expect_or_drop Bad rows would corrupt downstream results, and losing them is acceptable
Fail the update ... ON VIOLATION FAIL UPDATE @dp.expect_or_fail A violation means something is badly wrong, for example a broken source

Dropping loses evidence. When someone needs to fix or replay bad records, quarantine them: route rows that fail the rule to a separate table instead of discarding them.

rules = {"valid_id": "order_id IS NOT NULL", "valid_amount": "amount >= 0"}
all_rules = " AND ".join(f"({r})" for r in rules.values())

@dp.table
@dp.expect_all_or_drop(rules)
def silver_orders():
    return spark.readStream.table("bronze_orders")

@dp.table(comment="Rows that failed a silver rule, kept for review")
def quarantine_orders():
    return spark.readStream.table("bronze_orders").where(f"NOT ({all_rules})")

Each rule is written once, in the dictionary, so the silver table and the quarantine table cannot drift apart. Rows where a rule evaluates to null need care: NOT (NULL) is null, so wrap conditions with coalesce(..., false) if nulls must land in quarantine.

Streaming table or materialized view?

Streaming table Materialized view
Processes Only new input since the last update The query’s full result, refreshed incrementally where possible
Best for Append-heavy ingestion, bronze and silver, CDC targets Aggregates, joins and gold tables that must reflect changes and deletes in their sources
Latency Low; can run continuously Refreshed per update or on a schedule
Watch out Rows already processed are not recomputed if the logic changes, unless you do a full refresh Refresh cost grows if Databricks cannot compute it incrementally

A rule of thumb: stream into the layers that only grow, materialize the layers that summarise.

Declarative pipelines or Structured Streaming?

Choose a declarative pipeline when you want the platform to manage dependencies, checkpoints, retries, data quality metrics and CDC, and your logic fits tables defined by queries. Choose plain Structured Streaming in a job when you need full control. Examples are custom foreachBatch logic that writes to several sinks, arbitrary stateful processing, unusual sources or sinks, and code that must also run outside Databricks. Many platforms use both. The Structured Streaming lesson covers watermarks, output modes and checkpoints for the hand-written path.

Reading the event log

Every pipeline writes an event log: updates, flow progress, data quality results, errors and lineage. Query it with the event_log() function and the pipeline ID:

SELECT timestamp,
       origin.flow_name,
       details:flow_progress.data_quality.dropped_records AS dropped_records
FROM event_log('<pipeline-id>')
WHERE event_type = 'flow_progress'
  AND details:flow_progress.data_quality IS NOT NULL
ORDER BY timestamp DESC
LIMIT 50;

Build a small dashboard or alert on top of it: rising dropped-record counts usually mean a source changed before anyone told you.

Operating pipelines

  • Triggered or continuous. Triggered pipelines process what is available and stop, which is cheaper and fits most batch schedules. Continuous pipelines keep running for low latency.
  • Development mode reuses compute and does not retry, for fast iteration; production mode restarts on failure.
  • Full refresh recomputes streaming tables from scratch. It can be expensive, and if the source no longer holds all history (a Kafka topic with short retention) data can be lost. Protect such tables from full refreshes.
  • Requirements. AUTO CDC needs serverless pipelines or the Pro or Advanced edition, and it is a Databricks feature, not part of open-source Apache Spark Declarative Pipelines.

Common mistakes

  1. Hand-written MERGE for CDC without ordering. Late events overwrite newer ones. Use AUTO CDC with SEQUENCE BY.
  2. SCD Type 2 on every column. Noise columns create endless versions; limit with TRACK HISTORY ON.
  3. Dropping bad rows silently. Quarantine them and alert on the counts.
  4. Changing streaming table logic and expecting old rows to change. Only new input is processed; plan a full refresh or a backfill.
  5. Full refresh on a table whose source has expired data. You cannot rebuild what the source no longer has.

Interview angle

“How would you build a customer dimension with history from a database CDC feed on Databricks?” Land the feed in a bronze streaming table, apply it with AUTO CDC STORED AS SCD TYPE 2 keyed on the customer ID and sequenced by the source log position. Handle deletes with APPLY AS DELETE WHEN, limit history to meaningful columns, add expectations with a quarantine table, and monitor the event log. Explain what __START_AT and __END_AT mean and how to query the current row.

Key takeaway

Let AUTO CDC handle ordering, deletes and history instead of writing MERGE logic by hand. Keep failed rows in a quarantine table rather than losing them. Stream into the layers that grow, materialize the layers that summarise, and watch the event log for data quality drift.

By , Data Engineer and Founder of DataDank · Last reviewed Nov 2026 · Describes Lakeflow Spark Declarative Pipelines (formerly Delta Live Tables) as documented in November 2026. AUTO CDC replaces APPLY CHANGES with the same syntax. AUTO CDC needs serverless pipelines or the Pro or Advanced edition and is not part of open-source Apache Spark Declarative Pipelines. The SQL and Python examples need a Databricks workspace and were checked against the documentation, not executed.

Progress is saved in this browser only. No account needed.

Search
Filter by type