← BuildandTeach Tech Tutorials posts

Published · By Henry Palma

Databricks Data Engineer Associate Exam Prep, Lesson 11: Data Quality Checks with Expectations and Constraints

Databricks Data Engineer Associate exam prep: data quality checks with pipeline expectations, CHECK constraints, and a filter-or-quarantine pattern.

Databricks Data Engineer Associate Exam Prep, Lesson 11: Data Quality Checks with Expectations and Constraints

Exam-style question: A pipeline loads Nov 4 orders into silver with CONSTRAINT valid_amount EXPECT (amount >= 0) and no ON VIOLATION clause. Order 5008 arrives with an amount of -15.00. Is it kept out of the table? No. It is written to the target table. An expectation with no action uses the default, warn, which writes invalid records and only counts the violation in the data quality metrics. To keep the row out, add ON VIOLATION DROP ROW, or use ON VIOLATION FAIL UPDATE to stop the update. This post follows Lesson 11 of the Databricks Data Engineer Associate exam prep series, in Section 3 of the August 2026 exam guide, Data Transformation and Modeling (22% of the exam).

Watch on YouTube

Video thumbnail
Video thumbnail

The notebook and cheat sheet are in the A11 folder on GitHub. The PDF cheat sheet is in the same folder. This is independent study material, not official Databricks training.

The exam objective

Section 3 of the exam guide lists this objective: apply data quality checks and validation rules to ensure reliable Silver and Gold datasets.

On the exam this usually comes down to one question: when a row breaks a rule, what happens to it? It can be written anyway, dropped, set aside for review, or it can stop the load. Each answer is right for some rules and wrong for others. The two traps are a check that only warns while bad rows still reach gold, and a check that fails the whole job over a problem that only affects one row.

Everything here fits in Databricks Free Edition. Expectations are a Lakeflow pipeline feature. Serverless pipelines run on the Advanced product edition, which includes expectations, and Free Edition allows one active pipeline per pipeline type. The quarantine code and the CHECK and NOT NULL results in this post were checked with a local Apache Spark 4.0 run with open-source Delta Lake, not on Databricks. Pipeline expectations cannot run locally, so those results are marked as expected, based on the Databricks docs.

The scenario: the Nov 4 orders batch

The retail dataset from Lessons 8 to 10 continues. silver.customers has four customers:

| customerid | customername | state | |---|---|---| | 101 | Ana Lopez | TX | | 102 | Ben Wu | TX | | 103 | Cara Diaz | CO | | 104 | Dev Shah | OK |

silver.orders holds orders 5001 to 5005 from Nov 2 and Nov 3, with order 5002 already at its updated amount of 36.00. On Nov 4, a new batch lands in bronze, bronze.orders_nov4:

| orderid | customerid | orderdate | amount | Problem | |---|---|---|---|---| | 5006 | 104 | 2026-11-04 | 25.00 | none | | 5007 | NULL | 2026-11-04 | 22.00 | null customerid | | 5008 | 103 | 2026-11-04 | -15.00 | negative amount | | 5009 | 105 | 2026-11-04 | 12.00 | customer 105 does not exist | | 5010 | 102 | 2026-11-04 | 31.50 | none |

The rule from the business: reject orders with a null customer_id or a negative amount, and do not let an order for an unknown customer reach silver either. The broken rows must not disappear, because someone has to fix them. Only 5006 and 5010 should reach silver.orders.

The quality checklist

Most validation rules fall into three groups:

  1. Not-null. Required keys are present: customer_id IS NOT NULL.
  2. Range. Values are possible: amount >= 0, a date that is not in the future.
  3. Referential. Keys point to something real: every customer_id in orders exists in customers.

For each rule, decide the action before you write any code:

  • Keep and count (warn). The problem is soft. You want to see how often it happens, but the row is still useful.
  • Drop. The row is useless downstream and you do not need to review it.
  • Quarantine. The row is wrong but someone needs to fix it. Keep the clean set in silver and write the bad rows, with a reason, to a separate table.
  • Fail. The problem means the whole batch cannot be trusted, for example a broken file or a missing key column. Stop the load.

Pipeline expectations: warn, drop, fail

In a Lakeflow pipeline, a data quality check is an expectation: a named constraint on a streaming table, materialized view, or view. The constraint is a SQL Boolean expression checked on every record. The action decides what happens to a record that fails:

| Action | SQL | Python | Invalid records | |---|---|---|---| | warn (default) | EXPECT (...) | dp.expect | Written to the target. The violation is counted in metrics. | | drop | EXPECT (...) ON VIOLATION DROP ROW | dp.expectordrop | Dropped before the write. The dropped count is logged. | | fail | EXPECT (...) ON VIOLATION FAIL UPDATE | dp.expectorfail | The update fails. Manual intervention is needed before reprocessing. |

Here is the drop version on the bronze streaming table from Lesson 10:

CREATE OR REFRESH STREAMING TABLE silver.orders_validated (
  CONSTRAINT valid_customer_id EXPECT (customer_id IS NOT NULL) ON VIOLATION DROP ROW,
  CONSTRAINT valid_amount      EXPECT (amount >= 0)            ON VIOLATION DROP ROW
) AS SELECT * FROM STREAM(bronze.orders_raw);

The same thing in Python:

from pyspark import pipelines as dp

@dp.table(name="silver.ordersvalidated") @dp.expectordrop("validcustomerid", "customerid IS NOT NULL") @dp.expectordrop("validamount", "amount >= 0") def ordersvalidated(): return spark.readStream.table("bronze.orders_raw") ```

Expected results for the Nov 4 batch, based on the docs:

  • Warn (remove ON VIOLATION DROP ROW): all 5 rows are written, including 5007 and 5008. The metrics show one failure for each expectation. This is the trap. The dashboard looks fine, and a negative order now flows into the gold totals.
  • Drop: 3 rows are written, 5006, 5009 and 5010. The metrics show 2 dropped records. Order 5009 still gets through, because no rule checks that customer 105 exists.
  • Fail (ON VIOLATION FAIL UPDATE): the first invalid record fails the update, and the table update is rolled back, so none of the 5 rows is written, including the good ones. That is the second trap: failing the whole load over two bad orders.

Two details are worth knowing for the exam. First, a constraint cannot contain a subquery that references another table, so a referential check needs a join before the expectation. Second, metrics are available for warn and drop. A fail stops the update, so no metrics are recorded for it. For a standalone streaming table or materialized view created in Databricks SQL, query the pipeline event log for these metrics.

Quarantine: keep the clean set, keep the bad rows

Dropping loses the rows. Failing loses the whole batch. When the bad rows need follow-up, split them instead. This is the reusable filter-or-quarantine snippet. It adds a reason column with withColumn, drops a helper column, and filters on the reason:

from pyspark.sql import functions as F

orders = spark.table("bronze.ordersnov4") customers = (spark.table("silver.customers") .select("customerid") .withColumn("known_customer", F.lit(True)))

checked = (orders .join(customers, "customerid", "left") .withColumn("dqreason", F.when(F.col("customerid").isNull(), "null customerid") .when(F.col("amount").isNull() | (F.col("amount") < 0), "bad amount") .when(F.col("knowncustomer").isNull(), "unknown customer")) .drop("knowncustomer"))

clean = checked.filter(F.col("dqreason").isNull()).drop("dqreason") quarantine = checked.filter(F.col("dq_reason").isNotNull())

assert orders.count() == clean.count() + quarantine.count()

clean.select("orderid", "customerid", "orderdate", "amount") \ .write.mode("append").saveAsTable("silver.orders") quarantine.write.mode("append").saveAsTable("silver.ordersquarantine") ```

Local run:

| Output | Rows | |---|---| | clean | 5006 (104, 25.00), 5010 (102, 31.50) | | quarantine | 5007 null customer_id, 5008 bad amount, 5009 unknown customer | | counts in / clean / quarantine | 5 / 2 / 3 | | silver.orders after the append | 7 rows |

Why the snippet is written this way:

  • One reason column, then two filters. Each row gets exactly one label, so every row lands in exactly one table. The assert proves nothing was lost.
  • The left join is the referential check. Customer 105 has no match, so known_customer is null and the row is quarantined as an unknown customer.
  • Nulls are handled on purpose. A filter keeps only rows where the condition is true. In the local run, a row with a NULL amount passed neither filter("amount >= 0") nor filter("NOT (amount >= 0)"), so a naive good-or-bad split would silently lose it. The snippet checks isNull() first.

Databricks documents the same quarantine idea for pipelines: one table with all records and an is_quarantined flag, plus a view for the valid rows and a view for the invalid rows.

Table constraints: NOT NULL and CHECK

Expectations live in pipelines. A Delta table can also guard itself with enforced constraints, whoever writes to it:

ALTER TABLE silver.orders ALTER COLUMN customer_id SET NOT NULL;
ALTER TABLE silver.orders ADD CONSTRAINT non_negative_amount CHECK (amount >= 0);

Both commands first verify that every existing row passes. After that, any write that breaks a constraint fails the whole transaction with an error. In the local run, an insert of order 5008 (-15.00) together with a valid order 5012 failed with DELTAVIOLATECONSTRAINTWITHVALUES, and an insert of 5007 failed with DELTANOTNULLCONSTRAINTVIOLATED. The table still had 7 rows, and 5012 was not written either. Open-source Spark rejects ALTER COLUMN ... SET NOT NULL, so the local run declared NOT NULL in the table schema instead. The ALTER form above is the documented Databricks syntax.

So a CHECK constraint behaves like fail, not like drop. Use it as the last guard on silver and gold, and quarantine bad rows before the write so one bad order does not block the rest. Primary key and foreign key constraints on Databricks are informational only and are not enforced, so they do not replace a referential check.

Practice exam-style question

A data engineer wants every order in a pipeline's silverorders table to have a matching customer in silver.customers. They write CONSTRAINT knowncustomer EXPECT (customerid IN (SELECT customerid FROM silver.customers)). What is the best fix?

  • A) Add ON VIOLATION DROP ROW to the same constraint
  • B) Declare a foreign key constraint on silverorders.customerid, because Databricks enforces it on every insert
  • C) Left join orders to customers in the dataset query, select c.customerid AS matchedcustomerid, and add EXPECT (matchedcustomer_id IS NOT NULL)
  • D) Switch the expectation to dp.expect, because Python expectations allow subqueries

Answer: C. Expectation constraints cannot contain subqueries that reference other tables, so the lookup has to happen in the query first. After a left join, an unknown customer shows up as a null matchedcustomerid, and a plain expectation on that output column can catch it. The Databricks missing-record pattern works the same way: left join, then expect the joined key to be not null. A keeps the invalid subquery. B is wrong because foreign key constraints on Databricks are informational and not enforced. D is wrong because the same constraint rules apply in Python.

Key takeaways

  • An expectation with no ON VIOLATION clause only warns: invalid rows are still written to the target.
  • ON VIOLATION DROP ROW drops invalid rows and logs the count. ON VIOLATION FAIL UPDATE stops the update and rolls it back.
  • When bad rows need follow-up, quarantine them: one reason column, then a clean table and a quarantine table, with counts that add up.
  • NOT NULL and CHECK constraints fail the whole write, so check rows before writing. Referential checks need a join.
  • Memory trick: warn writes, drop drops, fail stops.

Next lesson (Lesson 12): Spark tuning basics.

Check your understanding

1. A pipeline table has CONSTRAINT valid_amount EXPECT (amount >= 0) with no ON VIOLATION clause. A record arrives with amount -15.00. What happens?

  • A) The record is dropped
  • B) The update fails
  • C) The record is written to the target and the violation is counted
  • D) The record is moved to a quarantine table automatically

2. Which Python decorator drops invalid records before they are written?

  • A) dp.expect
  • B) dp.expectordrop
  • C) dp.expectorfail
  • D) dp.expect_all

3. What does ON VIOLATION FAIL UPDATE do when one invalid record arrives?

  • A) Writes the valid records and drops the invalid one
  • B) Writes everything and logs a warning
  • C) Fails the update and rolls it back, so manual intervention is needed before reprocessing
  • D) Retries the record three times

4. silver.orders has CHECK (amount >= 0). One INSERT writes order 5008 with -15.00 and order 5012 with 9.00. What is written?

  • A) Only 5012
  • B) Only 5008
  • C) Both rows
  • D) Neither row, because the whole insert fails

5. A DataFrame row has a NULL amount. Which filter keeps it?

  • A) filter("amount >= 0")
  • B) filter("NOT (amount >= 0)")
  • C) Both of them
  • D) Neither of them

Answer key

  1. C. Warn is the default action. Invalid records are written to the target, and the violation shows up in the metrics.
  2. B. expectordrop drops invalid records and logs the dropped count. expect warns and expectorfail fails.
  3. C. Fail stops the update. For a table update, the transaction is rolled back.
  4. D. A CHECK violation fails the whole transaction. In the local run, 5012 was not written either.
  5. D. amount >= 0 is NULL for a NULL amount, and so is its negation. A filter keeps only rows where the condition is true, so check isNull() first.

Have an idea, question, or feedback?

We'd genuinely like to hear from you.