CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 3 · Lesson 21/45

    Pipeline expectations: warn, drop, fail and quarantine bad records

    Implement data quality expectations in Lakeflow Pipelines to quarantine, drop, or fail on bad records.

    19 min read
    3% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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.

    The same expectation in Python and SQL: a name plus a Boolean constraint, with no action givensql
    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);

    Checkpoint 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?

    Sources12

    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.

    The three expectation actions and how each is written
    ActionSQLPythonViolating rowMetrics
    warn (default)EXPECT (...)dp.expectWritten to the targetPassed and failed counts recorded
    dropEXPECT (...) ON VIOLATION DROP ROWdp.expect_or_dropRemoved before the writeDropped count logged with the dataset metrics
    failEXPECT (...) ON VIOLATION FAIL UPDATEdp.expect_or_failStops the update, which is rolled backNot 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.

    All three actions on a chain of streaming tables: warn on raw, drop on clean, fail on criticalsql
    -- 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.

    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?

    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?

    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?

    Sources13

    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.

    One dictionary of rules reused with three different group actionspython
    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 dataset

    A 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?

    Sources145

    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.

    Flag-column quarantine: inverted rules compute is_quarantined while expect_all records the metricspython
    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.

    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?

    Sources543

    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.

    Sources1

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 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. 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. 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

    Spotted a mistake, or was something unclear? Tell us.