CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 3 · Lesson 16/33

    Data quality checks: expectations, quarantine and Delta constraints

    Apply data quality checks and validation rules to ensure reliable Silver and Gold datasets

    22 min read
    3.14% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    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.

    Sources12

    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.

    A streaming table with one named expectation. No ON VIOLATION clause is given, so this rule only warns.sql
    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?

    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.

    The three violation actions in SQL and Python, and what each does to an invalid row
    ActionSQL syntaxPython syntaxInvalid rowUpdate
    warn (default)EXPECTdp.expectWritten to the targetContinues; pass/fail counts are logged
    dropEXPECT ... ON VIOLATION DROP ROWdp.expect_or_dropDropped before the writeContinues; the dropped count is logged
    failEXPECT ... ON VIOLATION FAIL UPDATEdp.expect_or_failStops the flowRolled 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?

    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?

    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?

    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.

    Valid rows go to silver and the exact complement goes to a quarantine table, using two separate writessql
    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;

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

    Sources43

    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.

    The six Python expectation decorators. They go after the dataset decorator and before the function.python
    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.

    Sources356

    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.

    A materialized view that fails if two tables have different row countssql
    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)

    Sources6

    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.

    Adding and then removing a CHECK constraint on an existing tablesql
    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.

    Declaring a composite primary key and a foreign key that references it. Neither is enforced on write.sql
    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);
    Rules on a table compared with rules on a pipeline dataset
    MechanismWhere it livesOn violationEnforced?
    NOT NULL / CHECKDelta table definitionTransaction fails with an errorYes, on every write
    PRIMARY KEY / FOREIGN KEY / UNIQUEDelta table definitionNothing; the write succeedsNo, informational only
    EXPECT (warn, drop, fail)Pipeline streaming table, materialized view or viewConfigurable: keep, drop, or fail the updateYes, within the pipeline

    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.

    Sources2

    Sources

    (6)

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

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

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