The six checks
Part of the free LogicWiz Data Engineering course, Module 7: Data quality and testing. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:10 on Monday. Maya Chen has received the same marketing email three times. Liam received nothing, because his customer row has no email address. Tess's product report shows a category called "(blank)", and one order line points at product 999, which does not exist. Nothing failed overnight. Every one of these had been sitting in the data for weeks.
You'll learn to
- Write the six standard checks as queries that return bad rows
- Catch a load that did not run with freshness and volume
- Run the same checks in Python with pandas
- Keep checks cheap on huge tables with partitions, estimates and samples
Learn
A check is a query that finds bad rows
Nobody looked. That is the whole story of this Monday: the data had been wrong for weeks, and nothing was asking.
A data check is a query that returns the rows that break a rule. Zero rows: the check passes. Any rows: it fails, and the rows themselves say what is wrong.
Think of a smoke alarm in a kitchen. It does nothing all day, and it is the only thing awake at 3 a.m. A check runs after every load. When it fails at 6:00, the person on call sees the offending rows straight away, not only "test failed".
The shape works everywhere: SQL, pandas, dbt. Six checks catch most real problems.
After every load: ask, then decide
A load finishes and a check query runs. If it returns zero rows the pipeline carries on; if it returns rows the pipeline stops or alerts, with those rows attached.
Follow the arrows: the check has two exits, and the red one carries the bad rows with it.
The six checks
| Check | The rule | At SwiftKart | Query shape |
|---|---|---|---|
| Not null | A column always has a value | Every customer has an email | WHERE email IS NULL |
| Unique | No value appears twice | One customer per email | GROUP BY email HAVING COUNT() 1 |
| Accepted values | Values come from a known list | Status is one of five | WHERE status NOT IN (...) |
| Referential integrity | Every foreign key has a parent | Every order line's product exists | LEFT JOIN products ... WHERE p.productid IS NULL |
| Freshness | The newest data is recent enough | An order changed in the last 24 hours | runtime - MAX(updatedat) INTERVAL '24 hours' |
| Volume | The row count is in a normal range | 3 to 12 orders a day | COUNT() against a range |
The first four look at rows. The last two look at the table as a whole. Start with the first two, on the customers table. Before you run them, answer one question.
Not null and unique on customers
-- Not null: customers we cannot email
SELECT customer_id, name
FROM customers
WHERE email IS NULL;
-- Unique: emails used by more than one customer
SELECT email, COUNT(*) AS customers
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;
Customer 7 has no email: that is why Liam got nothing. Three sign-ups share Maya Chen's email: that is why she got three. The unique check returns one row per repeated value, with how many times it appears.
An order line that points at nothing
The next two checks compare a value with something outside the row.
Accepted values: the value must come from a known list. An order's status must be one of five.
Referential integrity: a value that points at another table must find its row there. Every order line names a product, and that product must exist. A line that points at nothing is called an orphan.
The shop's own database would refuse such a line, because its tables are tied together by foreign keys. A landing table in the pipeline has no keys, so only a check catches it. The usual way to write it is a LEFT JOIN that keeps the rows whose partner is missing. Step through it.
Find the orphan with a LEFT JOIN
Landed order lines are left-joined to the products table. Lines whose product exists get a partner; the line for product 999 gets NULLs, and a filter on NULL returns that one line.
Two tables. The landed file holds the order lines of 2 June. Each names a
product_id. Theproductstable has ids 101 to 120.LEFT JOIN keeps every line. A line whose product exists gets that product's columns beside it.
No partner, so NULLs. Line 9 of order 1009 names product 999. Nothing matches. The row is kept anyway, with NULL in every product column.
WHERE p.product_id IS NULL. The filter keeps only the rows with no partner. One row comes back, so the check fails, and the row says which line to fix.
Watch the red box: the orphan survives the join, then the filter picks it out. A plain JOIN would have dropped it in step 2, and the check could never fail.
Accepted values and referential integrity
-- Accepted values: statuses the business has not defined
SELECT status, COUNT(*) AS orders
FROM orders
WHERE status NOT IN ('placed', 'shipped', 'delivered', 'cancelled', 'returned')
GROUP BY status;
-- Referential integrity: landed order lines whose product does not exist
SELECT i.order_id, i.line_no, i.product_id
FROM staging.order_items_landed AS i
LEFT JOIN products AS p ON p.product_id = i.product_id
WHERE p.product_id IS NULL;
The status check returns nothing: a pass. The second query finds the line for product 999 in the 2 June file (loaded here as staging.order_items_landed).
A load that did not run has no bad rows
Row checks share one blind spot. If last night's file never arrived, there are no bad rows. There are no rows at all, and every check passes.
Two checks look at the table as a whole.
Freshness asks how old the newest row is. The shop takes orders every hour. If the newest updated_at is two days old, something upstream is stuck, even though every row present is perfect.
Volume asks whether the row count is normal. Three orders on a day that usually has 300 means a file went missing or a filter broke. Compare with a fixed range, or with the same weekday last week.
Both need to know what "now" is. Pass the run time in, so a rerun gives the same answer.
Freshness on two mornings
A timeline in hours. Orders change until about 23:00 on 15 June. A check at 06:00 on 16 June finds the newest change 7 hours old and passes; with no new data, a check at 06:00 on 17 June finds it 31 hours old and fails.
Monday, 06:00. The newest
updated_atin the table is Sunday at about 23:00. The check runs 7 hours later. 7 is under 24, so freshness passes.Tuesday, 06:00, and Monday's load never ran. No new rows, so the newest change is still Sunday 23:00. Now it is 31 hours old. Every row in the table is still perfect, and freshness fails.
The axis is hours since midnight on Sunday 15 June, rounded. The second bar is the age of the newest row: it passes while it ends before the 24-hour line.
Freshness and volume, with a fixed run time
-- Freshness: how old is the newest change, at the 06:00 run on 16 June?
SELECT MAX(updated_at) AS newest_change,
TIMESTAMP '2025-06-16 06:00:00' - MAX(updated_at) AS age,
CASE WHEN TIMESTAMP '2025-06-16 06:00:00' - MAX(updated_at) > INTERVAL '24 hours'
THEN 'fail' ELSE 'pass' END AS freshness
FROM orders;
-- Volume: orders placed per day against an expected range of 3 to 12
SELECT order_ts::DATE AS day, COUNT(*) AS orders,
CASE WHEN COUNT(*) BETWEEN 3 AND 12 THEN 'pass' ELSE 'fail' END AS volume
FROM orders
GROUP BY order_ts::DATE
ORDER BY day;
The newest change is about 7 hours old: fresh. Every day has 5 or 6 orders: normal volume. Change the run time to 18 June and freshness fails.
SwiftKart's report card
| Check | Column | Failing | Verdict |
|---|---|---|---|
| not null | customers.email | 1 row (customer 7) | fail |
| unique | customers.email | 1 value used 3 times (Maya Chen) | fail |
| not null | products.category | 1 row (product 117) | fail |
| accepted values | orders.status | 0 | pass |
| relationships | landed lines to products | 1 row (product 999) | fail |
| freshness | orders.updatedat | about 7 hours old | pass |
| volume | orders per day | 5 or 6 a day | pass |
Four failures, each with the exact rows to fix. Some will be fixed at the source (Maya's duplicate accounts), some in the transform (a default category), and some by setting rows aside (Lesson 7.2).
The same checks in Python with pandas
import pandas as pd
customers = pd.read_csv('data/customers.csv')
products = pd.read_csv('data/products.csv')
items = pd.read_csv('landing/order_items/2025-06-02.csv')
results = {
'not_null customers.email': int(customers['email'].isna().sum()),
'unique customers.email': int(customers['email'].dropna().duplicated().sum()),
'not_null products.category': int(products['category'].isna().sum()),
'relationships items.product_id': int((~items['product_id'].isin(products['product_id'])).sum()),
}
for name, failing in results.items():
print(f"{'FAIL' if failing else 'pass'} {name}: {failing}")
isna() finds missing values. duplicated() marks every repeat after the first, so Maya's three sign-ups count as 2 extra copies. isin() tests whether a value is in the parent column. Same rules, different engine.
The trap: a check that can never fail. Two classics. WHERE email = NULL always returns zero rows, because nothing equals NULL. And a referential check written as WHERE product_id NOT IN (SELECT product_id FROM ...) returns zero rows as soon as the parent list holds one NULL. Both stay green forever. So test the check: break the data on purpose once, and watch it go red.
Three billion rows: check what you just wrote
On SwiftKart's 200-line tables every check is instant. Now picture the same checks on a table of 3 billion rows. An exact unique check reads every row and moves every key. Running the whole suite on the whole table every night costs more than the load itself.
Three habits keep checks cheap.
- Check the part you wrote tonight, not the whole table. Save its row count, null rates and distinct counts in a small metrics table, so tomorrow's volume check has days to compare.
- Estimate where a close answer is enough, such as distinct counts.
- Sample where the problem is common, such as null rates.
For uniqueness across the whole table, compare tonight's keys with the existing ones: an index lookup, a key table, or a MERGE that fails on a duplicate. Do not rescan history.
Gigabytes a nightly check scans: 3 years of 2 GB a day
Bars compare the data scanned by a check over the whole table, over tonight's partition, and over a one percent sample of that partition.
Compare the bar lengths: the whole-table check grows every day, the partition check stays flat. Keep a weekly or monthly full sweep for what partition checks cannot see.
Count distinct values in 12 KB
One check is costly however you cut it: how many different users came today? An exact COUNT(DISTINCT user_id) has to remember every value it has seen. 2 billion 8-byte ids are 16 GB of keys before any overhead.
HyperLogLog (HLL) gives up exactness and remembers almost nothing. It turns each value into random-looking bits (a hash) and watches for one rare event: a long run of zeros at the start. If someone tells you they flipped 10 heads in a row, you guess they have been flipping for a while. A run of 10 zeros says about a thousand different values have gone past.
One lucky run would fool it, so it keeps many small counters, called registers, and averages them.
One value goes into a HyperLogLog
A value is hashed to 64 bits; the first four bits choose one of sixteen registers; the zeros at the start of the remaining bits are counted; the register keeps the largest count it has seen; all registers together give the estimate.
Hash the value.
user-417becomes 64 bits that look random. The same value always gives the same bits, so seeing it twice changes nothing. Say its hash begins0001 0000 1....The first bits pick a register. With 16 registers, the first 4 bits choose one.
0001is register 1.Count the zeros. The rest of the hash starts with 4 zeros before its first 1. The number to remember is zeros plus one: 5.
Keep the largest. Register 1 becomes 5. A later value that lands in register 1 with only 1 leaves it at 5. That is all the work HLL does per row.
Estimate. After every row has gone through, each register holds its longest run. Only one hash in 16 starts with four zeros, so high numbers mean many different values passed. A special average over all the registers gives the count.
Follow the hash from the top box into one register below. The error is about 1.04 / sqrt(m) for m registers: 16,384 registers give 0.81% in about 12 KB. Two sketches merge by keeping the larger number per register, so daily sketches roll up into a monthly count without rereading a row.
A tiny HyperLogLog, then DuckDB's
import hashlib
import duckdb
P = 10 # 2**10 = 1,024 registers
M = 2 ** P
def hash64(value):
return int.from_bytes(hashlib.md5(str(value).encode()).digest()[:8], 'big')
def add(registers, value):
h = hash64(value)
idx = h >> (64 - P) # the first P bits pick a register
rest = h & ((1 << (64 - P)) - 1) # the other 54 bits
registers[idx] = max(registers[idx], (64 - P) - rest.bit_length() + 1)
def estimate(registers):
alpha = 0.7213 / (1 + 1.079 / M)
return alpha * M * M / sum(2.0 ** -r for r in registers)
events = [f'user-{i % 40000}' for i in range(100000)] # 100,000 events, 40,000 users
registers = [0] * M
for user in events:
add(registers, user)
est = estimate(registers)
print('exact', len(set(events)), '| estimate', round(est), '| off by', round(abs(est - 40000) / 400, 2), '%')
print('expected error about', round(104 / M ** 0.5, 2), '% from', M, 'registers')
exact, approx = duckdb.sql("""
SELECT COUNT(DISTINCT x), approx_count_distinct(x)
FROM (SELECT range % 750000 AS x FROM range(1000000))
""").fetchone()
print('DuckDB: exact', exact, '| approx_count_distinct', approx)
One kilobyte of registers estimates 40,000 distinct users within about 2%, close to the 3.25% the formula predicts for 1,024 registers. DuckDB's approx_count_distinct is HyperLogLog too, and so are the functions of Spark, Snowflake, BigQuery and Trino in the table at the end.
What a guess cannot prove
Estimates and samples answer "about how much?". They cannot answer "is there even one?".
So use HyperLogLog to watch a trend ("distinct customers fell 30% today"), and exact checks on tonight's partition for keys.
A sample measures a rate well. A 2% null rate measured on 10,000 sampled rows is off by about 0.14 points. But a sample is blind to rare rows. A 1% sample misses one bad row 99 times in 100. It misses all of 300 bad rows about 4.9% of the time: that is 0.99 multiplied by itself 300 times. One night in twenty, that check is green while the bad rows sit there.
Estimate a null rate from a 5% sample
-- Exact: scans all 200,000 rows
SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE user_id IS NULL) / COUNT(*), 2) AS null_pct_exact
FROM clicks;
-- Estimate: about 10,000 rows, the same ones on every run
SELECT COUNT(*) AS sampled,
ROUND(100.0 * COUNT(*) FILTER (WHERE user_id IS NULL) / COUNT(*), 2) AS null_pct_sample
FROM clicks TABLESAMPLE BERNOULLI (5) REPEATABLE (42);
The exact rate is 2.00%; the sample lands within a few tenths of a point of it. TABLESAMPLE BERNOULLI (5) picks each row with a 5% chance, and REPEATABLE (42) returns the same sample while the table is unchanged. Change the seed and the estimate moves a little. Change the check to "any NULL at all" and a sample is the wrong tool.
Remember: exact checks for rules that must hold on every row; estimates and samples for rates and trends. Put "exact" or "estimate" in the check's name, so nobody reads a green estimate as proof.
The same checks in dbt: schema.yml, then dbt test
Runs with dbt:
version: 2
models:
- name: stg_customers
columns:
- name: customer_id
data_tests: [unique, not_null]
- name: email
data_tests: [unique, not_null]
- name: stg_orders
columns:
- name: status
data_tests:
- accepted_values:
values: ['placed', 'shipped', 'delivered', 'cancelled', 'returned']
- name: customer_id
data_tests:
- relationships:
to: ref('stg_customers')
field: customer_id
$ dbt test --select stg_customers stg_orders
...
Completed with 2 errors and 0 warnings:
Failure in test not_null_stg_customers_email (models/staging/schema.yml)
Got 1 result, configured to fail if != 0
Failure in test unique_stg_customers_email (models/staging/schema.yml)
Got 1 result, configured to fail if != 0
Done. PASS=4 WARN=0 ERROR=2 SKIP=0 TOTAL=6
dbt ships four of the six as tests you switch on in YAML (not_null, unique, accepted_values, relationships), plus dbt source freshness. Each compiles to a query that returns failing rows, like the ones above: "Got 1 result" is the one NULL email, and the one repeated email. Great Expectations calls them expectations (expect_column_values_to_not_be_null), Soda writes them as YAML checks (missing_count(email) = 0), and Databricks pipelines declare expectations on each table. Module 8 runs dbt for real.
Numbers to remember
| What | Number or name | Good to know |
|---|---|---|
| HyperLogLog registers | m = 2^p | The first p bits of the hash pick a register; it keeps the longest run of leading zeros seen in the other bits, plus one |
| HyperLogLog estimate | alpha x m^2 / sum(2^-register) | A harmonic mean over all the registers |
| HyperLogLog error | about 1.04 / sqrt(m) | p = 14: 16,384 registers, 0.81%, about 12 KB at 6 bits a register. p = 10: 1,024 registers, 3.25% |
| Spark | approxcountdistinct(col, rsd) | HyperLogLog++; rsd defaults to 0.05 |
| Snowflake | APPROXCOUNTDISTINCT | Average relative error 1.62% |
| BigQuery | HLLCOUNT.INIT | Precision 15 by default, 10 to 24 |
| Trino | approxdistinct | 2.3% standard error |
| Error of a sampled rate | sqrt(p x (1 - p) / n) | A 2% rate on 10,000 rows: sqrt(0.02 x 0.98 / 10,000), about 0.14 points |
| Postgres sampling | TABLESAMPLE SYSTEM (p) or BERNOULLI (p) | SYSTEM takes whole pages: fast, but rows stored together come together. BERNOULLI takes each row independently |
What changed at SwiftKart
SwiftKart now runs the six checks after every load. Monday's four failures each came with their rows. Liam's missing email goes back to the team that owns sign-up, Maya's three accounts get merged at the source, product 117 gets a default category, and the line for product 999 is held back.
The big fact table gets exact checks on each night's partition and an estimate for its distinct counts. And each check was broken on purpose once, to prove it can go red.
A failing check leaves a question: what do you do with the bad rows? Stop the whole load, or set them aside and carry on? Lesson 7.2 writes the rules down as a contract and decides.
In one line
A check is a query that returns bad rows: run the six after every load, make sure each one can fail, and keep them cheap by checking what you just wrote.
Interview corner
Why are freshness and volume checks needed if every row passes its checks?
Because the most common failure is data that is missing, not data that is wrong. If yesterday's file never arrived, there are no bad rows to find; only "the newest row is too old" or "today has far fewer rows than usual" notices it.
How would you check that `order_id` is unique in a 5-billion-row fact table every night?
Not by rescanning it: an exact COUNT(DISTINCT) over 5 billion keys is a full scan and a full shuffle. I check the partition loaded tonight for duplicates within itself, then check its keys against the existing ones through something indexed or small: a key table, a MERGE that errors on a duplicate match, or a join only against the partitions those keys could live in. Approximate distinct counts cannot prove uniqueness, because 1,000 duplicates in 5 billion is far inside a 1% error. A periodic full sweep, say weekly, catches anything the incremental check could miss.
When is an approximate or sampled check good enough?
When the question is about a rate or a trend: distinct users per day with HyperLogLog (about 0.81% error at 16,384 registers, a few kilobytes, mergeable across days), or a null rate from a sample with a known standard error. It is not good enough for rules that must hold for every row, like unique keys or no negative amounts, because a 1% sample misses all of 300 bad rows about 5% of the time. I say which checks are exact and which are estimates in the check's name, so nobody reads a green estimate as proof.
How do you know a check works?
I make it fail on purpose: insert a NULL, a duplicate or an orphan row in a test or a dev copy and confirm the check returns it. Checks like = NULL or NOT IN against a list with a NULL look fine and can never fail.