From Quality Dimensions to Concrete Checks
Learn the quality dimensions (completeness, uniqueness, validity, consistency, accuracy, timeliness, plus volume and distribution), turn vague requirements into checks with a metric, a threshold and a schedule, and run nine of them in DuckDB against a small table with planted problems.
Contentsand lesson path
On this page
- Why it matters
- Eight ways data can be wrong
- From a vague wish to a check
- Find the rows behind a number
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Quality & Testing
- From Quality Dimensions to Concrete Checks Concept · 20 min
- Lab: Declarative Checks on Raw and Modeled Data Lab · 30 min
- Lab: Unit Tests for Transformation Logic Lab · 25 min
- Write-Audit-Publish and Quarantine Patterns Worked example · 25 min
- Lab: End-to-End Pipeline Tests with Disposable Databases Lab · 25 min
- Check: Triage a Failing Quality Suite Knowledge check · 10 questions
What you will learn
- Express quality requirements as measurable checks across completeness, uniqueness, validity, consistency, timeliness and accuracy.
01. Why it matters
Nobody asks for bad data, but almost nobody writes down what good data means. A stakeholder says "the orders table must be reliable", the pipeline team agrees, and three weeks later a dashboard shows revenue that is wrong in a way no one had a rule for. A requirement that cannot fail is not a requirement: there is nothing to run, nothing to alert on and nothing to fix.
A data quality check is a rule that a program can evaluate to pass or fail. To be useful it needs four parts: what it measures (a table, a column, a group of rows), the condition or metric (for example "share of rows with an email"), a threshold that separates pass from fail ("at least 99%"), and a schedule (when it runs, such as "after each load"). In this lesson you learn the usual ways data goes wrong, called quality dimensions, and you turn each one into a check that runs against a small DuckDB database.
02. Eight ways data can be wrong
The names below are the ones most teams and tools use. They overlap a little, and that is fine: their job is to make you ask every question once.
- Completeness: is a value there when it should be? A missing email on a customer row, or a whole day of orders that never arrived.
- Uniqueness: does each real-world thing appear once? The same order loaded twice doubles its revenue.
- Validity: does a value fit its format, type or allowed set?
eva@exampleis not an email address, andUKis not an ISO 3166 country code (the code isGB). - Consistency: do related values agree with each other? An order total should equal the sum of its order lines; a customer's country should be the same in the CRM and in billing.
- Accuracy: does the data match the real world, or a trusted source that stands for it? If the payment provider settled 20.00 for an order that you record as 25.00, your row is consistent with itself but wrong.
- Timeliness (often called freshness): is the data recent enough for its use? It is measured on the data itself, such as the age of the newest loaded row, not on whether a job ran.
Two more dimensions look at a whole batch rather than at single rows. Volume asks whether the number of rows is plausible compared with history. Distribution asks whether the shape of the values is plausible: the share of zero amounts, the mean, the number of distinct values. A batch can pass every row-level rule and still be wrong as a whole, for example when a bug sets a fifth of the amounts to zero.
Create a lab folder with a virtual environment and DuckDB, an in-process analytical database that needs no server. The lesson was tested with Python 3.12 and DuckDB 1.5.6.
mkdir dq-dimensions && cd dq-dimensions
python3 -m venv .venv && source .venv/bin/activate
pip install "duckdb==1.5.6"The script below builds a tiny shop database. One day of orders has a problem planted for each dimension, and three small tables play the roles that real reference data plays in production: the payment provider's settlement report, the list of valid country codes, and the row count and zero-amount share of the previous seven loads.
"""Build a tiny shop database with problems planted on purpose."""
import duckdb
con = duckdb.connect("shop.duckdb")
con.execute("""
CREATE OR REPLACE TABLE orders AS SELECT * FROM (VALUES
(1, '[email protected]', 'GB', 40.00, TIMESTAMP '2026-11-02 08:05'),
(2, '[email protected]', 'FR', 35.50, TIMESTAMP '2026-11-02 09:40'),
(3, '[email protected]', 'DE', 25.00, TIMESTAMP '2026-11-02 11:15'),
(4, NULL, 'GB', 61.20, TIMESTAMP '2026-11-02 12:30'),
(5, '[email protected]', 'UK', 55.00, TIMESTAMP '2026-11-02 14:05'),
(6, 'eva@example', 'ES', 0.00, TIMESTAMP '2026-11-02 15:20'),
(7, '[email protected]', 'IE', 18.90, TIMESTAMP '2026-11-02 16:45'),
(7, '[email protected]', 'IE', 18.90, TIMESTAMP '2026-11-02 16:45'),
(8, '[email protected]', 'IT', 0.00, TIMESTAMP '2026-11-02 19:10'),
(9, '[email protected]', 'GB', 72.40, TIMESTAMP '2026-11-02 23:40')
) AS t(order_id, email, country, total, loaded_at)""")
con.execute("""
CREATE OR REPLACE TABLE order_lines AS SELECT * FROM (VALUES
(1, 40.00), (2, 35.50), (3, 25.00), (4, 61.20), (5, 30.00),
(5, 20.00), (6, 0.00), (7, 18.90), (8, 0.00), (9, 72.40)
) AS t(order_id, line_amount)""")
# What the payment provider says it actually settled: a trusted reference.
con.execute("""
CREATE OR REPLACE TABLE settlements AS SELECT * FROM (VALUES
(1, 40.00), (2, 35.50), (3, 20.00), (4, 61.20), (5, 55.00), (7, 18.90),
(9, 72.40)
) AS t(order_id, settled)""")
con.execute("""
CREATE OR REPLACE TABLE countries AS
SELECT unnest(['DE', 'ES', 'FR', 'GB', 'IE', 'IT']) AS code""")
# Row count and share of zero totals for the previous seven loads.
con.execute("""
CREATE OR REPLACE TABLE load_history AS SELECT * FROM (VALUES
(DATE '2026-10-26', 10, 0.00), (DATE '2026-10-27', 12, 0.08),
(DATE '2026-10-28', 9, 0.00), (DATE '2026-10-29', 11, 0.09),
(DATE '2026-10-30', 10, 0.00), (DATE '2026-10-31', 12, 0.00),
(DATE '2026-11-01', 11, 0.09)
) AS t(load_date, row_count, zero_share)""")
for table in ["orders", "order_lines", "settlements", "countries", "load_history"]:
n = con.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
print(f"{table:<12} {n:>2} rows")python seed.pyorders 10 rows
order_lines 10 rows
settlements 7 rows
countries 6 rows
load_history 7 rows03. From a vague wish to a check
Take each wish and ask: what number would prove it? "Emails should be filled in" becomes "the share of today's orders with a non-null email is at least 0.99, checked after each load". "The data must be fresh" becomes "the newest loaded_at is at most 6 hours old, checked every 30 minutes". The threshold should come from the people who use the data: finance may accept a report that is a day old, while a support tool may need data from the last hour.
checks.py stores each check as data: the dimension, what it measures, the SQL that computes one number, an operator, a threshold and a schedule. A small loop runs every query and compares the result. Real frameworks such as dbt tests, Great Expectations and Soda work the same way underneath; you meet them in the next lab. The timeliness check uses a fixed AS_OF time so that your output matches the one below. In production it would use the current time.
"""Run measurable quality checks: each one is a metric, a threshold and a schedule."""
import operator
import duckdb
AS_OF = "TIMESTAMP '2026-11-03 07:00'" # in production: current_timestamp
OPS = {"<=": operator.le, ">=": operator.ge, "==": operator.eq}
CHECKS = [
# (dimension, what is measured, SQL for the metric, operator, threshold, when)
("completeness", "share of orders with an email",
"SELECT avg(CASE WHEN email IS NULL THEN 0 ELSE 1 END) FROM orders",
">=", 0.99, "after each load"),
("uniqueness", "order_id values seen more than once",
"SELECT count(*) - count(DISTINCT order_id) FROM orders",
"==", 0, "after each load"),
("validity", "emails that do not look like an address",
"SELECT count(*) FROM orders"
" WHERE NOT regexp_full_match(email, '[^@ ]+@[^@ ]+[.][a-z]{2,}')",
"==", 0, "after each load"),
("validity", "country codes not in the reference list",
"SELECT count(*) FROM orders WHERE country NOT IN (SELECT code FROM countries)",
"==", 0, "after each load"),
("consistency", "orders whose total differs from their lines",
"SELECT count(*) FROM (SELECT DISTINCT order_id, total FROM orders) o"
" JOIN (SELECT order_id, sum(line_amount) AS lines FROM order_lines"
" GROUP BY order_id) l USING (order_id) WHERE o.total <> l.lines",
"==", 0, "after each load"),
("accuracy", "orders that disagree with the provider",
"SELECT count(*) FROM (SELECT DISTINCT order_id, total FROM orders) o"
" JOIN settlements s USING (order_id) WHERE o.total <> s.settled",
"==", 0, "daily, when the settlement file lands"),
("timeliness", "hours since the newest loaded row",
f"SELECT date_diff('minute', max(loaded_at), {AS_OF}) / 60 FROM orders",
"<=", 6, "every 30 minutes"),
("volume", "rows loaded / 7-day average",
"SELECT (SELECT count(*) FROM orders) / avg(row_count) FROM load_history",
">=", 0.5, "after each load"),
("distribution", "zero-total share minus 7-day average",
"SELECT (SELECT avg(CASE WHEN total = 0 THEN 1 ELSE 0 END) FROM orders)"
" - avg(zero_share) FROM load_history",
"<=", 0.05, "after each load"),
]
con = duckdb.connect("shop.duckdb", read_only=True)
for dimension, measured, sql, op, threshold, when in CHECKS:
value = con.execute(sql).fetchone()[0]
status = "pass" if OPS[op](value, threshold) else "FAIL"
print(f"{status:<4} {dimension:<12} {measured}")
print(f"{'':6}{'':12} observed {round(value, 3)}, needs {op} {threshold}, {when}")python checks.pyFAIL completeness share of orders with an email
observed 0.9, needs >= 0.99, after each load
FAIL uniqueness order_id values seen more than once
observed 1, needs == 0, after each load
FAIL validity emails that do not look like an address
observed 1, needs == 0, after each load
FAIL validity country codes not in the reference list
observed 1, needs == 0, after each load
FAIL consistency orders whose total differs from their lines
observed 1, needs == 0, after each load
FAIL accuracy orders that disagree with the provider
observed 1, needs == 0, daily, when the settlement file lands
FAIL timeliness hours since the newest loaded row
observed 7.333, needs <= 6, every 30 minutes
pass volume rows loaded / 7-day average
observed 0.933, needs >= 0.5, after each load
FAIL distribution zero-total share minus 7-day average
observed 0.163, needs <= 0.05, after each loadRead a few results closely. The email validity check counts only order 6. Order 4 has no email at all, so regexp_full_match returns NULL, NOT NULL is still NULL, and the WHERE clause keeps only rows where the condition is true. That is deliberate: a missing value is a completeness problem, and counting it twice would blur the two signals. The consistency and accuracy checks use SELECT DISTINCT so that the duplicated order 7 does not distort them. The accuracy check runs on a different schedule, because it can only run when the provider's file has arrived.
The volume check passes: 10 rows against an average of about 10.7. The distribution check fails, because 20% of today's totals are zero against a usual 4%. Both would have passed a row-level test, since a zero is a valid amount.
04. Find the rows behind a number
A metric tells you that something is wrong. To fix it you need the rows. Keep a second query for each check that returns the offending records; dbt calls this storing failures, and you will use it in the next lab.
"""A metric says how many rows fail; a query of the failing rows says which ones."""
import duckdb
con = duckdb.connect("shop.duckdb", read_only=True)
con.sql("""
SELECT order_id, count(*) AS copies
FROM orders GROUP BY order_id HAVING count(*) > 1
""").show()
con.sql("""
SELECT o.order_id, o.total, sum(l.line_amount) AS sum_of_lines
FROM (SELECT DISTINCT order_id, total FROM orders) o
JOIN order_lines l USING (order_id)
GROUP BY o.order_id, o.total
HAVING o.total <> sum(l.line_amount)
""").show()python failing_rows.py┌──────────┬────────┐
│ order_id │ copies │
│ int32 │ int64 │
├──────────┼────────┤
│ 7 │ 2 │
└──────────┴────────┘
┌──────────┬──────────────┬───────────────┐
│ order_id │ total │ sum_of_lines │
│ int32 │ decimal(4,2) │ decimal(38,2) │
├──────────┼──────────────┼───────────────┤
│ 5 │ 55.00 │ 50.00 │
└──────────┴──────────────┴───────────────┘Choosing thresholds is the hard part, and there are three common sources:
- The business rule. Uniqueness of an order id and consistency of totals are usually zero-tolerance: one duplicate is already wrong.
- The consumer's need. Freshness and completeness thresholds come from what the report or model can live with.
- History. Volume and distribution have no correct value, only a usual range. Compute it from recent loads, as
load_historydoes, and compare today with it.
Think about the direction of each threshold too. The volume check above only has a lower bound, so a load that delivered every row twice would pass it; a uniqueness check or an upper bound would catch that. A threshold that is too tight produces alerts that people learn to ignore, and one that is too loose never fires. Start with values that the data owner agrees with, then adjust them from the alerts you see.
Finally, decide where each check runs. Checks on raw data at ingestion catch a broken source early and point to its owner. Checks after transformation catch your own bugs, such as a join that duplicates rows. Most pipelines need both, which is the subject of the next lab.
05. Check your understanding
06. Apply it
The skill practice asks for at least ten checks covering four dimensions on a pipeline of your own. Start now on paper, before any framework:
- List the tables your consumers read, and for each one write three checks in the form measure, threshold, schedule, with at least one batch-level check (volume or distribution).
- For each threshold, write where it comes from: a business rule, a consumer's need or history.
- Mark which checks can run on raw data at ingestion and which need the transformed tables.
07. Review prompt
Without looking back, name the eight dimensions and give one example check for each. Then explain why a check needs a schedule as well as a threshold, why accuracy needs a reference outside your own pipeline, and why a load that passes every row-level rule can still fail a distribution check.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.