Since the first lesson, Bookshop's three dirty rows (the doubled item 9, Maya's empty city, the 190 price) have been cleaned in the transform, because we know where they are. Tomorrow a fourth dirty row may turn up that you've never seen. That's what data quality validation is for: checking data against clear rules before anyone uses it, then deciding what happens when a rule is broken. It works like the person who receives goods at a minimarket's warehouse. When a truck arrives, they match the number of boxes against the delivery note and check expiry dates, price labels and goods delivered twice. Anything odd goes onto the returns shelf; the rest goes onto the racks. If the truck arrives empty, they stop receiving and call the sender. Bookshop's pipeline needs the same person: the checks, a returns shelf called quarantine, and a stop button.
Six dimensions of data quality
Each check measures one dimension of data quality:
| Dimension | Its question | At Bookshop |
|---|---|---|
| Completeness | is all the expected data there? | Maya's city is NULL; raw row count = source |
| Validity | do the values follow the format and rules? | a price must be between 1 and 100 |
| Accuracy | are the values true to reality? | $18 for a $19 book passes validity, yet it is still wrong |
| Consistency | does the data agree across tables and systems? | every book_id in an order exists in books |
| Timeliness | is the data recent enough? | the newest order is no older than 24 hours |
| Uniqueness | is anything doubled? | each order and book pair appears once |
Validity is the one checked most often: values that follow the format and rules. Accuracy is harder, because it needs a source of truth to compare with, such as the catalogue.
A check is a query that looks for offenders
The simplest way to write a check: one SELECT that looks for rows that break the rule. It passes when the result is 0 rows. Everything below runs in SQLite (the same as the Lab and the Playground) on raw_order_lines, the 19 raw rows from the ETL lesson.
-- unique: one row per (order_id, book_id) pair
SELECT item_id, order_id, book_id, qty
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY item_id) AS rn
FROM raw_order_lines)
WHERE rn > 1;
-- 9 | 6 | 2 | 2
-- not_null: the city must be filled in
SELECT item_id, customer, city FROM raw_order_lines WHERE city IS NULL;
-- 11 | Maya Sari | NULL
-- 19 | Maya Sari | NULL
-- accepted range: a sensible price
SELECT item_id, title, price FROM raw_order_lines
WHERE price NOT BETWEEN 1 AND 100;
-- 16 | The Dancer | 190
Three checks, three dirty rows caught. What if the unique check sits on item_id instead? The result is 0 rows: it passes. The retried job saved its copy with a new id (9), so item_id really is unique. A unique check must use the business key, the columns that really must not repeat in the real world: one book in one order.
Three more checks, and all three pass on today's data:
| Check | The query looks for | Result |
|---|---|---|
| relationships | order_items whose book_id is not in books (LEFT JOIN ... WHERE b.id IS NULL) |
0 rows |
| row count | a source row count that differs from raw | 19 = 19 |
| freshness | a newest order older than 24 hours | checked Saturday 06:00: 19.5 hours |
A check that passes still earns its place. raw_order_lines is built with a JOIN to books. If one day an admin deletes The Dancer from the catalogue, that JOIN silently drops its 4 order lines: relationships finds 4 offenders, and row count becomes 19 against 15. Freshness can change without anything breaking, too: checked on Monday at 06:00, the newest order (Friday 10:30) is 67.5 hours old.
Where checks run
- On load, as a gate. Raw lands, the checks run, and only then is
salesbuilt. In a Python or Airflow pipeline this is a step of its own before the transform. - In dbt (the dbt lesson comes later). Checks are written in YAML beside the model. dbt Core 1.12 has four built-in checks:
unique,not_null,accepted_values,relationships; thedbt_utilspackage 1.4 addsaccepted_rangeandunique_combination_of_columns.dbt testruns them;dbt buildruns models and checks in order and skips downstream models when a check fails. Every dbt check is also aSELECTthat looks for failing rows.
models:
- name: raw_order_lines
data_tests:
- dbt_utils.unique_combination_of_columns:
arguments:
combination_of_columns: [order_id, book_id]
columns:
- name: city
data_tests:
- not_null:
config:
severity: warn
- name: price
data_tests:
- dbt_utils.accepted_range:
arguments:
min_value: 1
max_value: 100
- In Python, with Great Expectations (GX Core 1.24.0). Its rules are called Expectations: declarative rules such as "this column must be unique" or "values must be between X and Y". The result is a validation report you can use as a gate in the pipeline.
import great_expectations as gx
import pandas as pd
df = pd.read_csv("order_lines.csv")
context = gx.get_context(mode="ephemeral")
batch = (
context.data_sources.add_pandas("bookshop")
.add_dataframe_asset("order_lines")
.add_batch_definition_whole_dataframe("all_rows")
.get_batch(batch_parameters={"dataframe": df})
)
suite = gx.ExpectationSuite(name="order_lines")
suite.add_expectation(gx.expectations.ExpectCompoundColumnsToBeUnique(column_list=["order_id", "book_id"]))
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(column="city"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="price", min_value=1, max_value=100))
result = batch.validate(suite)
print(result.success)
for r in result.results:
print(r.expectation_config.type, r.success, r.result["unexpected_count"])
False
expect_compound_columns_to_be_unique False 2
expect_column_values_to_not_be_null False 2
expect_column_values_to_be_between False 1
ExpectCompoundColumnsToBeUniquecounts 2: GX flags both twin rows (8 and 9), while the query above flags only the second copy (9).- Soda Core (4.26.0) does the same with a data contract in YAML:
missing,invalid,duplicate,freshness,row_countchecks.
When a check fails: stop or quarantine
Each check gets a severity. error means the data may not pass; warn means record it and tell someone, but carry on. Maya's NULL city is a warn: her sales are real, and the city is filled in as Unknown. The duplicate and the 190 price are errors. For an error check there are two choices:
- Stop the pipeline. The gate step raises an error,
salesis not rebuilt, the owner's report still shows yesterday's data, and whoever is on call gets a notification. This suits mistakes that touch every row: an empty extract, a missing column. - Quarantine. The failing rows move to a
quarantinetable with the name of their check, and the rest carries on:
CREATE TABLE quarantine AS
SELECT item_id, order_id, book_id, qty, price, 'unique' AS failed_check
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id, book_id ORDER BY item_id) AS rn
FROM raw_order_lines)
WHERE rn > 1
UNION ALL
SELECT item_id, order_id, book_id, qty, price, 'accepted_range'
FROM raw_order_lines
WHERE price NOT BETWEEN 1 AND 100;
Then sales is built from raw_order_lines with WHERE item_id NOT IN (SELECT item_id FROM quarantine). The result: 2 rows in quarantine (items 9 and 16), 17 rows in sales, and a reconciliation check: 19 raw rows = 17 + 2, nothing lost silently. The price: the owner's report is 1 book short (Rizky's order) until someone fixes item 16. When the fix is certain, like the catalogue price in the ETL lesson, just fix it in the transform. Quarantine is for what can't be fixed automatically.
⚠️ Checks that fool you, alarms that get ignored
- Unique on an auto id.
item_idis always unique, so a duplicate from a retry slips through. Check the business key:(order_id, book_id). - Everything is an error. If a
NULLcity stops the pipeline, the report halts over one customer who signed up with Google. Pick a severity per check. - Freshness that ignores the calendar. A 24-hour limit goes off every Monday morning if the shop is quiet at weekends. An alarm that rings too often ends up ignored.
- Quarantine without an owner. Quarantined rows need someone to check them and bring them back. Otherwise the report stays short and nobody knows.
TL;DR: Data quality is measured per dimension: completeness, validity (follows the format and rules), accuracy, consistency, timeliness, uniqueness. One check = one SELECT that looks for offenders; it passes at 0 rows. At Bookshop: unique on the business key (order_id, book_id) catches item 9 (unique on item_id passes instead), not_null catches Maya's 2 rows, an accepted range of 1 to 100 catches item 16; relationships, row count (19 = 19) and freshness pass today. Checks run as a gate on load, as dbt tests (unique, not_null, accepted_values, relationships), or with Great Expectations (Expectations such as ExpectColumnValuesToBeBetween) and Soda Core. On failure: severity warn carries on and tells someone, error stops the pipeline or moves the rows to quarantine, then checks that raw = sales + quarantine (19 = 17 + 2).
⚡ A check is a query that looks for offenders
Write:
SELECT item_id, customer, city FROM raw_order_lines WHERE city IS NULL;
Meaning: One check = one SELECT that looks for rows that break the rule. It passes when the result is 0 rows. This one finds Maya's 2 rows.
⚡ Unique on the business key
Guess first: the unique check sits on item_id. Is the doubled item 9 caught?
No, the check passes. The retried job saved its copy with a new id (9), so item_id really is unique. A unique check must use the business key: (order_id, book_id).
Meaning: The business key is the columns that really must not repeat in the real world: one book in one order.
⚡ Expectations
Write:
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(column="price", min_value=1, max_value=100))
Meaning: In Great Expectations, an Expectation is a declarative rule checked against the data, such as "values must be between X and Y". The result is a validation report you can use as a gate in the pipeline.
⚡ Warn, error, quarantine
Meaning: Severity warn means record it, tell someone, and carry on, like Maya's empty city. error means stop the pipeline, or move the rows to quarantine. Then reconcile: 19 raw rows = 17 + 2.