What you will be able to do
- Write a pipeline expectation with a name, a SQL Boolean constraint and the right violation action (warn, drop or fail)
- Predict what happens to invalid rows, metrics and the running update under each violation action
- Route failing rows to a quarantine dataset so they are kept for review instead of being discarded
- Build a validation dataset for checks that span tables, and explain why it does not stop downstream tables from updating
- Tell enforced Delta constraints (NOT NULL, CHECK) apart from informational primary and foreign keys
Key concept
Expectation violation action — Each pipeline expectation pairs a named SQL Boolean rule with an action that decides what happens to a row that fails it. The default action, warn, keeps the row and records metrics. Drop removes the row before the write. Fail stops the update. You choose the action according to how much damage an invalid row would do downstream.
1.Where quality checks belong in a medallion pipeline
The silver layer is where validation happens. Bronze holds raw data with only minimal checks, so that nothing is lost and anything can be reprocessed. Silver is the first layer analysts and data scientists are expected to trust. Gold aggregates silver, so a bad row that gets into silver ends up in a revenue total or a dashboard. Removing nulls, fixing types and replacing placeholder values is covered under data cleaning. Validation is a different job: you state rules that every row must satisfy, and you decide what happens to a row that breaks them.
Databricks gives you two places to state those rules. Pipeline expectations are attached to a streaming table, materialized view or view in a Lakeflow pipeline, and you can configure them to warn, drop or fail. Delta table constraints are attached to the table itself and reject any write that violates them, whatever process does the writing. A third technique is not a feature at all: quarantining, where you write failing rows to their own table so someone can inspect and reprocess them. In the reference medallion example, the silver step for customers and transactions does exactly this: it drops nulls and quarantines invalid records.
Checkpoint 1 of 10· Match them up
A silver layer combines three data quality techniques. Match each technique to the role it plays.
Tap a term, then the definition that fits it.
Expectations belong to the pipeline's dataset declarations and decide row by row what reaches the target. Delta constraints belong to the table and block any violating write. Quarantining is a pattern, not a feature: failing rows are written to their own table.
“You can choose to configure expectations to warn you about violations, drop violating records, or fail workloads based on violations.”Source: docs.databricks.com
2.Anatomy of a pipeline expectation
Every expectation has three parts: a name, a constraint and an action. The name identifies the rule in metrics and error messages, so make it describe what is checked, such as valid_customer_age. It must be unique within one dataset, although the same rule can be used on several datasets. The constraint is an ordinary SQL Boolean expression that is evaluated for each record. A record that evaluates to false triggers the expectation.
CREATE OR REFRESH STREAMING TABLE customers(
CONSTRAINT valid_customer_age EXPECT (age BETWEEN 0 AND 120)
) AS SELECT * FROM STREAM(datasets.samples.raw_customers);In SQL the keyword is EXPECT, written as CONSTRAINT <name> EXPECT (<clause>), and several expectations on one dataset are separated by commas. In Python each rule is its own decorator, such as @dp.expect("valid_customer_age", "age BETWEEN 0 AND 120"). Inside the parentheses you can use SQL functions, CASE expressions and compound AND/OR logic. For example, year(transaction_date) >= 2020 or a CASE that allows different status values for orders and for refunds are both valid constraints.
A constraint cannot contain custom Python functions, calls to external services, or subqueries that reference other tables. The last restriction is important: an expectation can only examine the row in front of it. A rule that compares two tables, such as "every order has a matching customer" or "no rows were lost between these tables", cannot be written as an expectation on a normal dataset. Those checks need a separate validation dataset, described later on this page.
Checkpoint 2 of 10· Check yourself
You are adding rules to an orders streaming table in a Lakeflow pipeline. Which proposed constraint clause cannot be used inside the parentheses of a CONSTRAINT ... EXPECT clause?
An expectation can only look at the row it is checking. A subquery against another table, such as checking that every order has a matching customer, is not allowed and needs a separate validation dataset. CASE expressions, SQL functions and compound AND/OR logic are all valid constraints.
“Subqueries referencing other tables”Source: docs.databricks.com
Sources3
3.Warn, drop or fail: choosing a violation action
Leaving out the action does not make a rule strict. A bare EXPECT only warns: the invalid row is written to the target with the valid rows, and the only trace is a pass/fail count. Use warn when you want to measure a quality problem before you decide how to handle it, or when the row is still useful despite the flaw.
| Action | SQL syntax | Python syntax | Invalid row | Update |
|---|---|---|---|---|
| warn (default) | EXPECT | dp.expect | Written to the target | Continues; pass/fail counts are logged |
| drop | EXPECT ... ON VIOLATION DROP ROW | dp.expect_or_drop | Dropped before the write | Continues; the dropped count is logged |
| fail | EXPECT ... ON VIOLATION FAIL UPDATE | dp.expect_or_fail | Stops the flow | Rolled back atomically; no metrics are recorded |
Drop is the right action when a row is useless downstream but the job has to keep running. For a nightly sensor load where a null sensor_id makes a reading meaningless, CONSTRAINT valid_sensor_id EXPECT (sensor_id IS NOT NULL) ON VIOLATION DROP ROW removes those rows before the write, and the rest of the update finishes normally. The pipeline records how many rows were dropped, so if the count suddenly rises you will see it in the metrics.
Fail is for data where a single bad row is unacceptable. If the update is a table update, the transaction is rolled back atomically, so the target is never left half-written. How far a failure spreads depends on the pipeline mode. In a triggered pipeline, only the failing flow fails, and parallel flows keep updating. In a continuous pipeline, the failing flow and every flow that depends on it stop. In both modes someone has to fix the pipeline code to handle the invalid data before the pipeline is run again. To help with that, the EXPECTATION_VIOLATION error message names the violated expectation and shows the input record that caused it.
Checkpoint 3 of 10· Check yourself
In a triggered pipeline, two independent streaming tables update in parallel: orders_silver has CONSTRAINT valid_count EXPECT (count > 0) ON VIOLATION FAIL UPDATE, and inventory_silver has no fail expectation and does not read from orders_silver. One order row has count = 0. What is the outcome of this update?
In a triggered pipeline, a fail expectation affects only the flow that breaks it. That flow's update is rolled back atomically, and parallel flows keep updating. A failed update records no metrics, and skipping a bad row is what drop does, not fail.
“In a triggered pipeline, the failure of a single flow does not cause other parallel flows to fail.”Source: docs.databricks.com
Checkpoint 4 of 10· Exam question
A Lakeflow Spark Declarative Pipeline loads raw sensor readings into a silver streaming table. Rows with a null sensor_id are unusable downstream, but the nightly update must keep running even when some rows fail this check. Which SQL constraint achieves this?
Correct answer: A — CONSTRAINT valid_sensor_id EXPECT (sensor_id IS NOT NULL) ON VIOLATION DROP ROW filters invalid rows out before the write and lets the rest of the update finish normally.
- A. The
DROP ROWviolation action removes rows that fail the constraint before they are written to the target, so bad rows are silently filtered while valid rows continue to flow and the update itself keeps running. This matches the requirement to keep nightly processing alive despite bad rows. - B.
FAIL UPDATEcauses the entire pipeline update to stop the moment any row violates the constraint, which is the opposite of the 'keep running' requirement described in the scenario. It is meant for critical checks where any violation should halt the whole run. - C. Omitting
ON VIOLATIONdefaults to the warn behavior, where invalid records are still written to the target table and only tracked as a quality metric. That leaves the nullsensor_idrows in the silver table, which does not satisfy the requirement. - D. Pipeline expectations use the
EXPECTkeyword, notCHECK;CHECKis a different SQL constraint concept used elsewhere and is not recognized inside a declarative pipeline expectation definition, so this statement would not work as intended.
Checkpoint 5 of 10· Exam question
When a pipeline expectation constraint is defined without specifying an ON VIOLATION clause, what is the default behavior for rows that fail the check?
Correct answer: A — Invalid rows are still written to the target, and the violation is only tracked as a data quality metric in the event log.
- A. The default action for an expectation with no explicit
ON VIOLATIONclause is the warn behavior: rows that fail the check are still written to the target, and the failure is only surfaced through data quality metrics for monitoring. No rows are removed or blocked. - B. Dropping invalid rows before the write is the behavior of the explicit
DROP ROWviolation action, not the default. Without specifying an action, rows are retained rather than filtered out. - C. Failing the entire update is the behavior of the explicit
FAIL UPDATEaction, which must be stated explicitly. It is not what happens when no violation action is configured. - D. Expectations never create a separate quarantine table automatically; any quarantine pattern has to be built by the engineer as a second dataset with an inverted condition, it is not a built-in default action.
Sources3
4.Quarantining invalid records instead of discarding them
Dropped rows cannot be recovered. The pipeline only keeps a count of them. That is a problem when an auditor asks to see every rejected record, or when a source system sends a batch of malformed rows that you will want to fix and load later. Quarantining solves this. The rows still stay out of the silver table, but they are written to a separate table where they can be inspected and reprocessed.
The pattern is to read the same source twice with complementary filters. The first write keeps the rows that pass the rules. The second write keeps the rows that fail them, using the inverted condition. Together the two tables account for every input row exactly once.
DECLARE current_time = now()
INSERT INTO silver_table
SELECT * FROM bronze_table
WHERE event_timestamp <= current_time AND quantity >= 0;
INSERT INTO quarantine_table
SELECT * FROM bronze_table
WHERE event_timestamp > current_time OR quantity < 0;Inverting the condition takes care. Under De Morgan's law, event_timestamp <= current_time AND quantity >= 0 becomes event_timestamp > current_time OR quantity < 0. If you get the inversion wrong, rows either appear in both tables or disappear from both. Also keep the two writes as separate operations. Databricks recommends this especially for Structured Streaming, because using .foreachBatch to write to several tables can produce inconsistent results.
Inside a Lakeflow pipeline you build the same pattern from expectations. The main silver dataset uses expect_or_drop with the rule, so only clean rows land in it. A second dataset reads the same source and uses expect_or_drop with the inverted rule, so it keeps only the rows the main table rejected. Both datasets get dropped-row metrics, nothing is lost, and the update keeps running. The other actions do not meet an audit requirement. expect_or_fail stops the update and leaves you to reprocess by hand. A bare expect leaves bad rows mixed into silver, where every downstream query has to filter them out. Malformed records at ingestion time are a schema problem and are handled by Auto Loader schema enforcement, not by quarantine logic.
Checkpoint 6 of 10· Fill the gap
This batch job must send every bronze row to exactly one of two tables: silver or quarantine. Which keyword completes the quarantine filter so that it is the exact complement of the silver filter?
DECLARE current_time = now()
INSERT INTO silver_table
SELECT * FROM bronze_table
WHERE event_timestamp <= current_time AND quantity >= 0;
INSERT INTO quarantine_table
SELECT * FROM bronze_table
WHERE event_timestamp > current_time ? quantity < 0;By De Morgan's law, NOT (A AND B) becomes (NOT A) OR (NOT B), so a row goes to quarantine if it breaks either rule. With AND, a row that breaks only one rule would be in neither table. With AND NOT, rows that break only the quantity rule would be in neither table, and rows that break only the timestamp rule would be in both.
Source: docs.databricks.comCheckpoint 7 of 10· Exam question
A compliance team wants every rejected row from a silver ingestion pipeline preserved for audit review, rather than simply discarded, while the clean rows still land in the main silver table. Which approach best satisfies this requirement using Lakeflow pipeline expectations?
Correct answer: A — Define a second table reading the same source with expect_or_drop on the inverted condition, so failing rows land in a quarantine dataset while the primary table drops them.
- A. Building a second dataset from the same source with the inverted condition and
expect_or_dropproduces exactly the two outputs the compliance team needs: a clean silver table and a separate quarantine table capturing rejected rows for audit, since expectations only support drop, warn, or fail on a single dataset. - B. Failing the whole update on any invalid row blocks all new data, including the valid rows, and does not produce a separate auditable record of what was rejected; it also requires manual, out-of-pipeline reprocessing rather than an automated audit trail.
- C. Leaving invalid rows mixed into the silver table with only a warning does not separate rejected rows for audit purposes, and pushing the filtering to Gold means the silver table itself remains unreliable in the meantime.
- D. The
_rescued_datacolumn captures data that does not match the expected schema during ingestion, which is a schema-evolution feature unrelated to expectation-based row validation and does not create an audit trail of rows failing a business rule.
5.Reading expectation metrics and stacking many rules
Warn and drop record metrics, but fail does not. Because a failed expectation stops the update, its pass/fail counts are never written. When you investigate a fail, you work from the error message and not from the dashboard. To see warn and drop metrics, go to Jobs & Pipelines, open the pipeline, click a dataset that has expectations, and open the Data quality tab in the right sidebar. The same numbers are in the pipeline event log, which you can query. For streaming tables and materialized views created in Databricks SQL, the event log is the only place to find them, because the Data quality tab is not available for those.
One dataset can carry several rules with different actions. For example, it can warn on a soft rule, drop on a structural one and fail on a critical one. In Python you can stack individual decorators, or pass a dictionary of rules to the expect_all variants. Each rule in that dictionary still reports its own metrics, so a dataset with ten rules shows which rule rejected which rows.
from pyspark import pipelines as dp
@dp.table()
@dp.expect(description, constraint)
@dp.expect_or_drop(description, constraint)
@dp.expect_or_fail(description, constraint)
@dp.expect_all({description: constraint, ...})
@dp.expect_all_or_drop({description: constraint, ...})
@dp.expect_all_or_fail({description: constraint, ...})
def <function-name>():
return (<query>)With dictionaries, you can keep the rules outside the pipeline code. Databricks recommends storing expectation definitions apart from pipeline logic, for example in a Delta rules table with name, constraint and tag columns. A small helper function then returns the rules for a given tag, such as validity, as a dictionary for @dp.expect_all_or_drop. Rules can then be audited and changed without editing the pipeline source. This works only in Python, because SQL does not support loading expectations dynamically.
Checkpoint 8 of 10· Match them up
A data engineer is looking into data quality problems in three datasets. For each situation, match where they will find the evidence.
Tap a term, then the definition that fits it.
Warn and drop record pass/fail or dropped-row metrics. You can see them in the Data quality tab, or only in the event log for datasets created in Databricks SQL. A fail stops the update before any metrics are written, so the error message is the evidence you have.
“Because fail causes the update to fail when an invalid record is detected, metrics are not recorded.”Source: docs.databricks.com
6.Validation tables for checks that span datasets
Some checks are about whole tables: whether a transformation lost rows, or whether every key in a source made it into a report. A per-row expectation cannot reference another table, so you create a dedicated validation dataset. Its query computes the property you want to check, and you put an expect_or_fail on its output. For background on the materialized views this pattern uses, see Gold layer objects.
CREATE OR REFRESH MATERIALIZED VIEW count_verification(
CONSTRAINT no_rows_dropped EXPECT (a_count == b_count)
) AS SELECT * FROM
(SELECT COUNT(*) AS a_count FROM table_a),
(SELECT COUNT(*) AS b_count FROM table_b)Referential checks work the same way. Left-outer-join a trusted copy of the keys to the report, select the report's key as r_key, and expect r_key IS NOT NULL. Any key that is missing from the report produces a null r_key, and the validation update fails.
No. A validation table detects the problem but does not stop other tables from updating. Reading from it does not make another dataset wait for its result, and in a triggered pipeline a failed expectation rolls back only its own flow. Expectations control which records reach a dataset. They do not decide whether other parts of the pipeline run. To stop downstream work when a validation fails, put the validation in one pipeline and the downstream tables in another, then run both from a job in which the downstream task depends on the validation task. A pipeline task fails when its update fails, so the downstream task never starts. Setting up those dependencies is covered under job task dependencies.
Checkpoint 9 of 10· Fill the gap
A row-count rule can't be a per-row expectation on table_a or table_b, so you declare a validation materialized view instead. Which keyword completes its rule so that it is a pipeline expectation?
CREATE OR REFRESH MATERIALIZED VIEW count_verification(
CONSTRAINT no_rows_dropped ? (a_count == b_count)
) AS SELECT * FROM
(SELECT COUNT(*) AS a_count FROM table_a),
(SELECT COUNT(*) AS b_count FROM table_b)A validation table is an ordinary pipeline dataset, so its rule uses the CONSTRAINT name EXPECT (...) form and evaluates the single row that the query computes. CHECK is the keyword for Delta table constraints, not pipeline expectations, and ASSERT and VALIDATE are not part of this syntax.
Source: docs.databricks.comSources6
7.Delta table constraints: enforced vs informational
Delta table constraints apply to every write to the table, not only writes from a pipeline. A notebook INSERT, a MERGE or another team's job is checked in the same way. There are two enforced types. NOT NULL means values in a column cannot be null. CHECK means a Boolean expression must be true for every input row. A constraint violation has only one outcome: the transaction fails with an error. A Delta constraint cannot warn, and it cannot drop the offending row.
ALTER TABLE main.default.people_demo ADD CONSTRAINT dateWithinRange CHECK (birthDate > '1900-01-01');
ALTER TABLE main.default.people_demo DROP CONSTRAINT dateWithinRange;You can only add a constraint to a table whose existing data already satisfies it. Before adding a CHECK or a NOT NULL with ALTER TABLE ... ALTER COLUMN ... SET NOT NULL, Databricks verifies all existing rows, so one existing null in the column blocks the change. A CHECK expression must be deterministic and cannot use user-defined functions, aggregate functions, window functions or functions that return multiple rows. That is why a CHECK can do a regex format check or a range check such as column_name >= 0 AND column_name <= 100, but cannot check uniqueness. Adding any constraint also upgrades the table's writer protocol if it is below version 3, which can affect external Delta Lake clients.
Primary keys, foreign keys and unique constraints are informational only. You declare them, they record the relationships between tables, and they may help query optimization, but Databricks does not enforce them. Two rows with the same primary key value are both written without any error. A foreign key must reference a primary key or unique constraint in another table, and you cannot declare these constraints in a CTAS statement.
CREATE OR REPLACE TABLE main.default.T(pk1 INTEGER NOT NULL, pk2 INTEGER NOT NULL,
CONSTRAINT t_pk PRIMARY KEY(pk1, pk2));
CREATE OR REPLACE TABLE main.default.S(pk INTEGER NOT NULL PRIMARY KEY,
fk1 INTEGER, fk2 INTEGER,
CONSTRAINT s_t_fk FOREIGN KEY(fk1, fk2) REFERENCES main.default.T);| Mechanism | Where it lives | On violation | Enforced? |
|---|---|---|---|
| NOT NULL / CHECK | Delta table definition | Transaction fails with an error | Yes, on every write |
| PRIMARY KEY / FOREIGN KEY / UNIQUE | Delta table definition | Nothing; the write succeeds | No, informational only |
| EXPECT (warn, drop, fail) | Pipeline streaming table, materialized view or view | Configurable: keep, drop, or fail the update | Yes, within the pipeline |
Put a Delta CHECK (amount >= 0) constraint on the table, so any writer that tries to insert a negative amount fails. In the pipeline, add EXPECT (amount >= 0) ON VIOLATION DROP ROW, so the pipeline removes those rows before it writes and never hits the table constraint. The expectation controls what the pipeline does with bad rows. The table constraint protects the table from every other writer.
Checkpoint 10 of 10· Match them up
Four rules guard a silver orders table. Match each rule to what happens when a row that breaks it is written.
Tap a term, then the definition that fits it.
NOT NULL and CHECK are the only enforced Delta constraints, and a violation fails the transaction for every writer. Primary key, foreign key and unique constraints are informational, so duplicate keys are written. Pipeline expectations act inside the pipeline: a bare EXPECT keeps the row and drop removes it.
“Primary key, foreign key, and unique constraints are informational only and aren't enforced.”Source: docs.databricks.com
Sources2
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Data cleanup and validation are performed in silver layer.”
↩︎ Where quality checks belong in a medallion pipeline“Data about customers and transactions is cleaned by dropping nulls and quarantining invalid records.”
↩︎ Where quality checks belong in a medallion pipeline - 2.
“When a constraint is violated, the transaction fails with an error.”
↩︎ Where quality checks belong in a medallion pipeline“CHECK: indicates that a specified boolean expression must be true for each input row.”
↩︎ Delta table constraints: enforced vs informational“Databricks verifies that all existing rows satisfy the constraint before adding a NOT NULL constraint to a table.”
↩︎ Delta table constraints: enforced vs informational“User-defined functions. Aggregate functions. Window functions. Functions returning multiple rows.”
↩︎ Delta table constraints: enforced vs informational“They might improve performance through query optimizations.”
↩︎ Delta table constraints: enforced vs informational“Foreign keys must reference a primary key or unique constraint in another table.”
↩︎ Delta table constraints: enforced vs informational“Primary key, foreign key, and unique constraints are informational only and aren't enforced.”
↩︎ Exam trap 4“Primary key, foreign key, and unique constraints are informational only and aren't enforced.”
↩︎ Checkpoint - 3.https://docs.databricks.com/aws/en/ldp/expectationsOfficial docs
“Expectations are optional clauses in pipeline materialized view, streaming table, or view creation statements”
↩︎ Anatomy of a pipeline expectation“An expectation name must be unique for a given dataset.”
↩︎ Anatomy of a pipeline expectation“Subqueries referencing other tables”
↩︎ Anatomy of a pipeline expectation“Invalid records are dropped before data is written to the target.”
↩︎ Warn, drop or fail: choosing a violation action“If the operation is a table update, the system atomically rolls back the transaction”
↩︎ Warn, drop or fail: choosing a violation action“In a continuous pipeline, an expectation failure stops the flow, all dependent flows”
↩︎ Warn, drop or fail: choosing a violation action“you must fix the pipeline code to handle the invalid data correctly before re-running the pipeline”
↩︎ Warn, drop or fail: choosing a violation action“You can also implement advanced logic to quarantine invalid records without failing or dropping data.”
↩︎ Quarantining invalid records instead of discarding them“Because fail causes the update to fail when an invalid record is detected, metrics are not recorded.”
↩︎ Reading expectation metrics and stacking many rules“You must specify an action to determine what happens when a record fails the validation check.”
↩︎ Key concept“Records that violate the expectation are added to the target dataset along with valid records”
↩︎ Exam trap 1“In a triggered pipeline, the failure of a single flow does not cause other parallel flows to fail.”
↩︎ Exam trap 2“Retaining invalid records is the default behavior for expectations.”
↩︎ Prediction“In a triggered pipeline, the failure of a single flow does not cause other parallel flows to fail.”
↩︎ Checkpoint - 4.
“You can use filters and WHERE clauses to define custom logic that quarantines bad records and prevents them from propagating to downstream tables.”
↩︎ Quarantining invalid records instead of discarding them“Using .foreachBatch to write to multiple tables can lead to inconsistent results.”
↩︎ Quarantining invalid records instead of discarding them“You can choose to configure expectations to warn you about violations, drop violating records, or fail workloads based on violations.”
↩︎ Checkpoint - 5.
“When you use expect_all decorators, each expectation has its own description and reports granular metrics.”
↩︎ Reading expectation metrics and stacking many rules - 6.
“Dynamically loading expectations from a file is not supported in SQL.”
↩︎ Reading expectation metrics and stacking many rules“Reading a validation table from another dataset doesn't make that dataset wait for the validation result”
↩︎ Validation tables for checks that span datasets“Expectations enforce data quality, not orchestration.”
↩︎ Validation tables for checks that span datasets“split the validation logic and the downstream work into separate pipelines and orchestrate them with a job”
↩︎ Validation tables for checks that span datasets“A validation table doesn't gate its downstream tables.”
↩︎ Exam trap 3