What you will be able to do
- Declare a named expectation in Python or SQL with a valid Boolean constraint
- Choose between warn, drop and fail for a constraint and write the matching decorator or ON VIOLATION clause
- Predict what an expect_or_fail violation does in triggered and continuous pipelines
- Build a quarantine path that keeps invalid rows instead of dropping them
Key concept
Expectation — A named SQL Boolean constraint on a pipeline dataset. It is evaluated on every row, and its action decides what happens to a row that evaluates to false: keep it and count it (warn), remove it (drop), or stop the flow's update (fail).
1.Name, constraint and action
Bad records reach a pipeline all the time: a negative price, an order with no customer, a timestamp from 1970. In Lakeflow Declarative Pipelines, the way to catch them is an expectation, an optional clause on a streaming table, materialized view or temporary view that checks every row the dataset's query produces. Each dataset is kept up to date by a flow, the part of the pipeline that reads from a source and writes into that target dataset, and expectations are evaluated as rows pass through it. You can stack several expectations on one dataset and put them on any dataset in the pipeline. Each expectation has three parts: a name, a constraint and an action.
The name identifies the expectation in metrics and error messages, so make it say what it checks, such as valid_customer_age rather than check1. A name must be unique within its dataset, but other datasets can reuse it. In Python the name is the first argument to the decorator. In SQL it follows the CONSTRAINT keyword.
CREATE OR REFRESH STREAMING TABLE customers(
CONSTRAINT valid_customer_age EXPECT (age BETWEEN 0 AND 120)
) AS SELECT * FROM STREAM(datasets.samples.raw_customers);The constraint is a standard SQL Boolean expression that returns true or false for each row. A false result triggers the expectation. The expression can be a simple comparison like price >= 0, a call to a built-in function like year(transaction_date) >= 2020, a CASE statement that checks status against a different list for each type, or several conditions joined with AND and OR. Three things are not allowed in a constraint: custom Python functions, calls to external services, and subqueries that reference other tables. Each row has to be judged on its own values, so a rule like "this order's customer exists in the customers table" can't go inside a constraint.
On a materialized view the constraint is limited further. It may use literals, the view's columns and deterministic built-in functions, but not aggregate, analytic window, ranking window or table-valued generator functions. Adding expectations also costs a materialized view its incremental refresh: it is fully recomputed on every update. If that matters, apply the checks upstream instead, a trade-off that ties into choosing a streaming table or a materialized view.
The action decides what happens to a row that fails. Of the three parts it has the biggest effect, and the next section covers it.
Checkpoint 1 of 9· Fill the gap
Which keyword completes this streaming table's data quality expectation?
CREATE OR REFRESH STREAMING TABLE customers(
CONSTRAINT valid_customer_age ? (age BETWEEN 0 AND 120)
) AS SELECT * FROM STREAM(datasets.samples.raw_customers);In SQL, a pipeline expectation is written with the name after CONSTRAINT and the row-level Boolean condition in brackets after EXPECT. CHECK is a different kind of table constraint, not a pipeline expectation.
Source: docs.databricks.comCheckpoint 2 of 9· Check yourself
A materialized view in a pipeline refreshes incrementally. An engineer adds a CONSTRAINT ... EXPECT clause to its definition. What happens on later pipeline updates?
Adding expectations to a materialized view turns off incremental refresh, so the view is fully recomputed on every update. If refresh cost matters, put the checks on an upstream dataset or take them out of the view's definition.
“A materialized view whose definition includes expectations is fully refreshed on each update and does not support incremental refresh.”Source: docs.databricks.com
2.Choosing warn, drop or fail
Warn is the default, so an expectation with no action keeps bad rows. A SQL CONSTRAINT ... EXPECT (...) with no ON VIOLATION clause, or a Python @dp.expect, writes violating rows to the target together with the valid ones. The pipeline counts how many rows passed and how many failed. Nothing is dropped, nothing fails, and no quarantine table appears unless you build one. Use warn when you need every record but want to see how much of the data is bad.
| Action | SQL | Python | Violating row | Metrics |
|---|---|---|---|---|
| warn (default) | EXPECT (...) | dp.expect | Written to the target | Passed and failed counts recorded |
| drop | EXPECT (...) ON VIOLATION DROP ROW | dp.expect_or_drop | Removed before the write | Dropped count logged with the dataset metrics |
| fail | EXPECT (...) ON VIOLATION FAIL UPDATE | dp.expect_or_fail | Stops the update, which is rolled back | Not recorded, because the update fails |
Drop removes the row and the flow keeps running. Use expect_or_drop when a bad row must never reach the target but its arrival is no reason to stop. Take a silver table that must never hold a null customer_id, has to keep processing later batches, and needs a count of what it rejected. That is @dp.expect_or_drop("valid_customer_id", "customer_id IS NOT NULL"). The SQL form is the same EXPECT keyword followed by ON VIOLATION DROP ROW. SQL has no EXPECT_OR_DROP keyword, so @dp.expect_or_drop("valid_order_amount", "order_amount > 0") becomes CONSTRAINT valid_order_amount EXPECT (order_amount > 0) ON VIOLATION DROP ROW.
Fail treats one bad row as an emergency. With expect_or_fail, or ON VIOLATION FAIL UPDATE in SQL, the flow stops at the first violation, and if the operation was a table update the transaction is rolled back atomically. Use it for conditions that should stop the world, such as a broken primary key. Fail costs you metrics, because the update never completes and so pass and fail counts are never recorded. It also costs you manual work: before you run the pipeline again, you have to change the pipeline code so it handles that data correctly.
-- Warn: write invalid records but track them in metrics
CREATE OR REFRESH STREAMING TABLE orders_raw (
CONSTRAINT valid_order_id EXPECT (order_id IS NOT NULL)
) AS SELECT * FROM STREAM read_files("/volumes/raw/orders", format => "json");
-- Drop: discard invalid records before writing
CREATE OR REFRESH STREAMING TABLE orders_clean (
CONSTRAINT non_negative_amount EXPECT (amount >= 0) ON VIOLATION DROP ROW
) AS SELECT * FROM STREAM(orders_raw);
-- Fail: stop the pipeline on any invalid record
CREATE OR REFRESH STREAMING TABLE orders_critical (
CONSTRAINT required_customer_id EXPECT (customer_id IS NOT NULL) ON VIOLATION FAIL UPDATE
) AS SELECT * FROM STREAM(orders_clean);Checkpoint 3 of 9· Match them up
Each expectation setting below has a different effect on a row that fails its constraint. Match each setting to that effect.
Tap a term, then the definition that fits it.
Warn is the default, so an EXPECT with no ON VIOLATION keeps bad rows and only counts them. Drop removes rows and records a count. Fail stops the update and rolls it back, so no metrics are recorded for that run. None of the actions creates a quarantine table; you have to build one yourself.
“Retaining invalid records is the default behavior for expectations.”Source: docs.databricks.com
Checkpoint 4 of 9· Exam question
In Lakeflow Declarative Pipelines, when a SQL CONSTRAINT ... EXPECT (...) clause is defined without an ON VIOLATION clause, what happens to records that violate the constraint?
Correct answer: B — The violating records are still written to the target table, and the violation is counted in the pipeline's quality metrics.
- A. A hard failure and rollback is the behavior of the fail action, which requires an explicit
ON VIOLATION FAIL UPDATEclause. Without that clause, the pipeline does not stop on a violation. - B. This describes the default warn behavior: no
ON VIOLATIONclause means violating rows are still written downstream while the count of violations is tracked in the dataset's data quality metrics. This is the least restrictive of the three actions. - C. Silently dropping rows with no tracked count describes neither the default action nor the drop action, since drop still logs how many rows were removed. The default action does not remove rows at all.
- D. There is no built-in automatic quarantine table; a quarantine destination has to be built manually using a derived flag column and separate downstream views or tables. A bare
EXPECTclause does not create any such routing.
Checkpoint 5 of 9· Exam question
A pipeline dataset is defined with the following Python decorator:
@dp.expect_or_drop("valid_order_amount", "order_amount > 0")
def silver_orders():
return spark.readStream.table("bronze_orders")
Which SQL CONSTRAINT clause is functionally equivalent to this Python decorator?
Correct answer: A — CONSTRAINT valid_order_amount EXPECT (order_amount > 0) ON VIOLATION DROP ROW, which drops rows failing the check and keeps the flow running.
- A.
ON VIOLATION DROP ROWis the SQL equivalent of theexpect_or_dropdecorator: violating rows are excluded from the target while the flow keeps processing later batches. This matches the drop-and-continue behavior shown in the Python code. - B.
ON VIOLATION FAIL UPDATEmaps toexpect_or_fail, notexpect_or_drop, so it would halt and roll back the update instead of just excluding the bad rows. This is a stricter action than the one in the decorator. - C. A bare
EXPECTclause with noON VIOLATIONsuffix is the SQL equivalent of the plainexpectdecorator, which only warns and still writes invalid rows. That does not match the drop behavior requested. - D. SQL constraint syntax expresses the action through the
ON VIOLATIONclause rather than through a keyword named after the Python decorator, soEXPECT_OR_DROPis not valid Lakeflow Declarative Pipelines SQL syntax.
Checkpoint 6 of 9· Exam question
A data engineer is building a silver-layer streaming table in a Lakeflow Declarative Pipeline. The business requirement states that records with a null customer_id must never reach the silver table, but the pipeline should keep processing subsequent batches even when such records occur, and the team wants a running count of how many rows were removed. Which decorator should the engineer apply to the transformation function?
Correct answer: B — @dp.expect_or_drop("valid_customer_id", "customer_id IS NOT NULL"), which excludes the null rows from the output while logging how many were removed.
- A. Rolling back the flow on every violation would stop processing entirely rather than letting the pipeline keep running, which conflicts with the requirement to keep processing subsequent batches.
- B. This satisfies all three requirements at once: null rows are excluded before reaching the silver table, the flow keeps processing later batches, and the number of dropped rows is tracked in the dataset's quality metrics.
- C. A plain expectation only warns and still writes the offending rows to the target table, which violates the requirement that null customer IDs must never reach the silver table.
- D. Grouping the rule under a fail-on-violation decorator still stops the entire update the moment a null appears, which is the same halting behavior as a single fail decorator and does not keep the pipeline running.
3.Grouped expectations and how far a failure reaches
Only Python can apply one action to a group of expectations. SQL lets you list several CONSTRAINT clauses separated by commas, each with its own action. Python adds expect_all, expect_all_or_drop and expect_all_or_fail, which take a dictionary that maps each expectation name to its constraint. Each entry still keeps its own name and reports its own metrics, so grouping does not merge the counts. The action works the same way as the single-expectation version: expect_all_or_fail is still fail. Wrapping a rule in a dictionary does not turn it into drop.
valid_pages = {"valid_count": "count > 0", "valid_current_page": "current_page_id IS NOT NULL AND current_page_title IS NOT NULL"}
@dp.table
@dp.expect_all(valid_pages)
def raw_data():
# Create a raw dataset
@dp.table
@dp.expect_all_or_drop(valid_pages)
def prepared_data():
# Create a cleaned and prepared datasetA rules dictionary like this doesn't have to sit in the pipeline file. Because the decorators accept any dictionary, you can keep rules in a Delta table or a Python module, give each rule a tag, and have a small get_rules(tag) function pass the matching rules to expect_all_or_drop for each dataset. This keeps rules in one place, so you can audit and update them without editing pipeline code. It only works in Python, because SQL can't load expectations dynamically.
How far a failure reaches depends on the run mode. A triggered pipeline processes all available data and then stops, so each run is a single update. A continuous pipeline keeps its cluster running and processes new data as it arrives. In a triggered pipeline, a failed expectation fails and rolls back only that flow's update, and the other flows carry on. In a continuous pipeline, it stops the flow and every flow that depends on it, and the pipeline emits a message saying why it stopped. Either way you get a dedicated EXPECTATION_VIOLATION error. A fail expectation changes the query plan so it can track which row caused the problem, so for many queries the error shows the violated expectation, the input record and the output record, for example a sensor reading of -500.
Expectations decide which rows reach a table. They do not decide whether other tables run. A dataset that reads a validation table does not wait for that validation to pass. To keep downstream work from running after a failed check, put the check and the downstream tables in separate pipelines and connect them with task dependencies in Lakeflow Jobs.
Checkpoint 7 of 9· Check yourself
In a triggered pipeline, a validation materialized view uses expect_or_fail. Other tables in the same pipeline read from it. The team wants those downstream tables to skip their update whenever the validation fails. What should they do?
Expectations control which rows reach a table, not whether other tables run. A dataset that reads a validation table doesn't wait for the validation to pass. To gate downstream work, split it into a separate pipeline and make that pipeline's task depend on the validation pipeline's task in a job. Grouping with expect_all_or_fail is still a fail action, and in triggered mode it fails only its own flow.
“split the validation logic and the downstream work into separate pipelines and orchestrate them with a job”Source: docs.databricks.com
4.Quarantining invalid rows instead of losing them
Drop keeps the target clean, but the rejected rows are gone for good. The count tells you that 4,000 rows had no customer_id. It doesn't let you look at those rows, fix their source, or load them again. If you need any of that, quarantine the rows. Pair a drop on the main table with a quarantine table that holds what was dropped. Then you can investigate, fix and reprocess the bad data without mixing it into your clean dataset.
There are two common ways to build a quarantine. The first uses two flows into separate tables. One flow writes the main table with the rules as drop expectations. The other flow reads the same source and keeps only the rows that fail. The trick in that second flow is the inverted expectation: take the rules, join them with AND, wrap the result in NOT(...), and filter on it. A row passes the inverted filter exactly when it fails at least one rule, so between them the two tables hold every row once.
The second way uses a flag column. A single intermediate table keeps every row and adds a Boolean column computed from the inverted rules. A warn-level expect_all on the same rules still records pass and fail metrics. Downstream views then split the rows on the flag, so valid and invalid rows go down separate paths. The example below adds is_quarantined and partitions on it.
rules = {
"valid_pickup_zip": "(pickup_zip IS NOT NULL)",
"valid_dropoff_zip": "(dropoff_zip IS NOT NULL)",
}
quarantine_rules = "NOT({0})".format(" AND ".join(rules.values()))
@dp.view
def raw_trips_data():
return spark.readStream.table("samples.nyctaxi.trips")
@dp.table(
temporary=True,
partition_cols=["is_quarantined"],
)
@dp.expect_all(rules)
def trips_data_quarantine():
return (
spark.readStream.table("raw_trips_data").withColumn("is_quarantined", expr(quarantine_rules))
)The clean path is a view that reads trips_data_quarantine and filters on is_quarantined=false. The quarantine path filters on the opposite value. The expectation here is plain expect_all, not drop. Dropping would delete the invalid rows before the flag could route them anywhere, which defeats the purpose.
Rows with amount = 0 are now dropped from the main table, but they don't match the quarantine's old inverted filter NOT(amount >= 0), so they end up in neither table. Build both sides from the same rules dictionary so they can't drift apart.
Checkpoint 8 of 9· Check yourself
A silver table drops rows with @dp.expect_all_or_drop on two rules, rule1 and rule2. Auditors now need to inspect, fix and reload every rejected row, and the clean table must stay free of bad rows. What should the engineer add?
Drop keeps only a count, so the rows must be routed to a second flow. Its filter inverts the combined rules with NOT(... AND ...), which catches any row that fails at least one rule. NOT(rule1) AND NOT(rule2) catches only rows that fail both rules. Fail stops the update at the first bad row and records no metrics.
“one that drops invalid rows from the main table and a second that writes only the invalid rows to a quarantine table”Source: docs.databricks.com
5.Where expectations apply and where their metrics appear
Expectations only work on streaming tables, materialized views and temporary views. Data quality metrics exist only for those objects. Flows that write to sinks, operators that don't support expectations, and flows that made no updates in a run produce no metrics. Expectations are not supported at all with AUTO CDC FROM SNAPSHOT, so plan quality checks around snapshot-based CDC rather than on it. A view is computed only when it is queried. A view may therefore show no metrics, or one set of metrics for each downstream dataset that reads it.
To see the numbers, open the pipeline under Jobs & Pipelines, click a dataset that has an expectation, and select the Data quality tab in the right sidebar. Warn and drop actions show up there. Fail actions do not. Streaming tables and materialized views created from Databricks SQL don't have this tab, so you get their metrics by querying the pipeline event log, the subject of monitoring data quality through event logs. Before a pipeline runs unattended, check that you know the current pass rate, not just that expectations exist.
Checkpoint 9 of 9· Match them up
An engineer is looking for expectation metrics in four situations. Match each situation to what the engineer will find and where.
Tap a term, then the definition that fits it.
Warn and drop record counts that appear on the Data quality tab. Fail stops the update, so no metrics are recorded for that run. Tables created from Databricks SQL have no Data quality tab, so you query the event log instead. Sinks don't support expectations, so they produce no metrics.
“Because fail causes the update to fail when an invalid record is detected, metrics are not recorded.”Source: docs.databricks.com
Sources1
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/ldp/expectationsOfficial docs
“An expectation name must be unique for a given dataset.”
↩︎ Name, constraint and action“Constraints must use valid SQL syntax and cannot contain the following:”
↩︎ Name, constraint and action“Invalid records are dropped before data is written to the target.”
↩︎ Choosing warn, drop or fail“If the operation is a table update, the system atomically rolls back the transaction”
↩︎ Choosing warn, drop or fail“you must fix the pipeline code to handle the invalid data correctly before re-running the pipeline.”
↩︎ Choosing warn, drop or fail“only Python allows you to group multiple expectations and specify collective actions.”
↩︎ Grouped expectations and how far a failure reaches“Expectations are not supported with AUTO CDC FROM SNAPSHOT.”
↩︎ Where expectations apply and where their metrics appear“Select the Data quality tab in the right sidebar.”
↩︎ Where expectations apply and where their metrics appear“apply data quality checks on each record passing through a query”
↩︎ Key concept“Invalid records are written to the target.”
↩︎ Exam trap 1“Because fail causes the update to fail when an invalid record is detected, metrics are not recorded.”
↩︎ Exam trap 2“Retaining invalid records is the default behavior for expectations.”
↩︎ Checkpoint“In a triggered pipeline, the failure of a single flow does not cause other parallel flows to fail.”
↩︎ Prediction“Because fail causes the update to fail when an invalid record is detected, metrics are not recorded.”
↩︎ Checkpoint - 2.
“A materialized view whose definition includes expectations is fully refreshed on each update and does not support incremental refresh.”
↩︎ Name, constraint and action“A materialized view whose definition includes expectations is fully refreshed on each update and does not support incremental refresh.”
↩︎ Exam trap 5 - 3.
“fail for conditions that should stop the world (such as a broken primary key)”
↩︎ Choosing warn, drop or fail“drop for records you can safely discard (with a quarantine table capturing what was dropped)”
↩︎ Quarantining invalid rows instead of losing them - 4.
“In a continuous pipeline, a failed expectation stops the flow and all dependent flows.”
↩︎ Grouped expectations and how far a failure reaches“Expectations enforce data quality, not orchestration.”
↩︎ Grouped expectations and how far a failure reaches“Dynamically loading expectations from a file is not supported in SQL.”
↩︎ Grouped expectations and how far a failure reaches“enable separate processing paths for valid and invalid records in downstream operations”
↩︎ Quarantining invalid rows instead of losing them“split the validation logic and the downstream work into separate pipelines and orchestrate them with a job”
↩︎ Checkpoint - 5.
“Triggered mode processes all available data and then stops.”
↩︎ Grouped expectations and how far a failure reaches“Continuous mode keeps the cluster running and processes new data as it arrives.”
↩︎ Grouped expectations and how far a failure reaches“This lets you investigate, fix, and reprocess bad data without contaminating your clean dataset.”
↩︎ Quarantining invalid rows instead of losing them“a second that writes only the invalid rows to a quarantine table”
↩︎ Exam trap 4“one that drops invalid rows from the main table and a second that writes only the invalid rows to a quarantine table”
↩︎ Checkpoint
Also cited
“This expectation causes a failure of a single flow and does not cause other flows in your pipeline to fail.”
↩︎ Exam trap 3