How-To Guide

How to Implement Data Quality Checks with SQL Assertions

Guard data pipelines with SQL assertions for nulls, uniqueness, referential integrity, freshness and ranges, failing the job when data is wrong.

On this page

  1. Introduction
  2. The Five Classes of Assertion
  3. Freshness and Volume Assertions
  4. Wiring Assertions into the Pipeline
  5. Quarantine and Root-Cause Capture
  6. Testing the Checks Themselves
  7. Common Pitfalls and Conclusion

Introduction

A pipeline that runs to completion is not a pipeline that produced correct data. Silent corruption, where a job writes nulls into a required column, duplicates a batch, or breaks a foreign key, is far more damaging than a crash, because downstream consumers trust the output and nobody notices until a report is wrong a week later. Data quality checks are assertions you run against the data itself, and the most portable form is SQL: a query that returns the offending rows, which fails the job when it returns anything at all.

The Five Classes of Assertion

Most data quality problems fall into a handful of classes. Completeness checks that required columns are not null. Uniqueness checks that the primary key is unique. Referential integrity checks that foreign keys point at rows that exist. Freshness checks that the newest timestamp is recent enough. Range and domain checks that values fall in a sane set, such as a status in an allowed enum or a count that is not negative.

Each class is a SQL query that returns rows violating the rule. The assertion passes when the query returns zero rows and fails otherwise. This shape is language-agnostic, works against any warehouse, and produces the offending rows as evidence rather than a bare boolean.

-- Completeness: required columns must be present.
SELECT id FROM orders WHERE customer_id IS NULL OR total_cents IS NULL;

-- Uniqueness: primary key must not repeat.
SELECT id, COUNT(*) FROM orders GROUP BY id HAVING COUNT(*) > 1;

-- Referential integrity: values must have a matching parent.
SELECT DISTINCT o.customer_id
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL;

Freshness and Volume Assertions

Freshness catches the job that ran but loaded nothing, usually because an upstream table was empty or a filter matched no rows. Assert that the maximum timestamp in the table is within an expected window, expressed relative to now, so the check does not go stale. Volume assertions catch the opposite failure, a load that produced far fewer or far more rows than usual.

Set volume bounds from the recent distribution rather than a fixed number, because traffic legitimately varies. A row count between a fraction and a multiple of the trailing median catches the dropped partition and the duplicated load while tolerating normal variation. Report the observed count alongside the bounds so a failure is self-explaining.

-- Freshness: newest row must be recent enough.
SELECT 'stale' AS problem, MAX(created_at) AS newest
FROM events
HAVING MAX(created_at) < now() - INTERVAL '15 minutes';

-- Volume: today's count must stay within bounds of the trailing median.
WITH recent AS (
  SELECT event_date, COUNT(*) AS n
  FROM events
  GROUP BY event_date
  ORDER BY event_date DESC
  LIMIT 8
),
stats AS (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY n) AS med FROM recent)
SELECT today.n, stats.med
FROM (SELECT COUNT(*) AS n FROM events WHERE event_date = current_date) today, stats
WHERE today.n < stats.med * 0.5 OR today.n > stats.med * 2.0;

Wiring Assertions into the Pipeline

Run the assertions immediately after the load and before the job marks itself successful. Each assertion is a query; if it returns rows, capture a sample, emit a structured error and fail the job so downstream tasks do not consume bad data. Failing fast is the point: an assertion that only logs is a dashboard nobody reads.

Make severity explicit. Some checks are critical and must stop the pipeline; others are warnings that should be recorded but not block, such as an unusual but legal distribution. Encode the severity in the check definition so the runner decides whether to fail or merely annotate, rather than every check failing the job.

checks:
  - id: orders.pk_unique
    severity: critical
    sql: SELECT id, COUNT(*) FROM orders GROUP BY id HAVING COUNT(*) > 1
  - id: orders.freshness
    severity: critical
    sql: SELECT MAX(created_at) FROM orders HAVING MAX(created_at) < now() - INTERVAL '1 hour'
  - id: orders.status_domain
    severity: warning
    sql: SELECT status FROM orders WHERE status NOT IN ('new','paid','shipped','refunded')

Quarantine and Root-Cause Capture

When an assertion fails, capture enough context to diagnose it. Store the check id, the time, the offending row count and a sample of rows in a results table. This turns “quality check failed” into “3,412 rows in orders had a null customer_id starting at 02:14”, which is actionable.

Route the bad data to a quarantine table where the row shape allows it, so a single malformed batch does not corrupt the main table and can be repaired and replayed. Quarantine is most useful for row-level failures; table-level failures such as a wrong row count are better handled by refusing to promote the load at all.

Keep a quality results table that records every check run, its status, the observed value and a link to the sample. This history is valuable in two ways: it shows whether a failure is new or chronic, and it lets you backtest a proposed threshold against what actually happened. Without a history, every incident starts from zero context and every threshold is a guess.

Testing the Checks Themselves

A quality check that never fires is indistinguishable from one that is broken. Test each assertion against a fixture with a known violation and confirm it returns the offending rows, then against clean data and confirm it returns none. This is especially important after a schema change, which is when assertions silently stop matching.

Also guard against the opposite error, a check so strict it pages on normal variation. Backtest each new check against historical data to see how often it would have fired. A freshness check that alarms every Monday because weekend traffic is low will be muted within a month, taking the real alerts with it.

-- Fixture-based test of the uniqueness assertion.
CREATE TEMP TABLE orders (id bigint, customer_id bigint);
INSERT INTO orders VALUES (1, 10), (1, 11), (2, 12); -- id 1 duplicated

-- Expect exactly one offending group (id = 1).
SELECT id, COUNT(*) FROM orders GROUP BY id HAVING COUNT(*) > 1;

TRUNCATE orders;
INSERT INTO orders VALUES (1, 10), (2, 11); -- clean
-- Expect zero rows.
SELECT id, COUNT(*) FROM orders GROUP BY id HAVING COUNT(*) > 1;

Common Pitfalls and Conclusion

Do not run quality checks only on a schedule after the fact; run them in the pipeline before data is promoted. Do not write assertions that depend on now() without accounting for time zones and backfills, or historical replays will fail spuriously. Do not let warnings and criticals share a channel, or criticals get muted with the noise. And do not treat a green check as proof of correctness: assertions bound the failure modes you enumerated, not every possible one.

SQL assertions are the cheapest high-value quality control available to a data team. Express each rule as a query that returns violators, run them before the job succeeds, capture evidence when they fire, and test the checks themselves. The objective is not zero failures; it is that no failure reaches a consumer unnoticed.

Sources: PostgreSQL: Aggregate functions, dbt: Tests, Great Expectations: Expectations gallery.

FAQ

Why express checks as queries returning rows instead of booleans?
A query that returns the offending rows gives you evidence for free: the count, a sample and the shape of the failure. A boolean only tells you something is wrong, which forces a second query to investigate.
Should a failed quality check always fail the pipeline?
Critical checks should, because promoting bad data is worse than stopping. Non-critical checks should warn without blocking. Encode severity per check so the runner decides, rather than making every failure fatal.

Related Examples