npNick Paolini

NOTE No.23 · ■ Data · · 6 min read

Test Your Data Like You Test Code

Six SQL checks that catch the most common kinds of broken data before it reaches a dashboard, or an AI assistant that will repeat it with total confidence.

Software teams don't ship code without tests anymore. Data teams ship tables without them all the time, and then find out something broke when someone in a meeting says "that number can't be right."

The irony is that data tests are easier to write than most code tests. A data test is just a query that returns the rows that break a rule. Zero rows means pass. That's the whole convention, and it's the one dbt and most data-quality tools use under the hood.

This matters more now than it did a few years ago. A dashboard with a bad number at least looks like a dashboard: someone might notice a weird dip. An AI assistant answering questions from the same table will state the bad number in a confident, well-written sentence. Garbage in, eloquent garbage out.

Here are the six checks I'd put on any table that feeds a report.

Uniqueness: the grain is what you think it is

Every table has a grain: one row per account per day, one row per order. A lot of broken metrics come down to a join that silently changed it, leaving two rows where there should be one and doubling a sum.

-- Expect: one row per account per day
SELECT account_id, snapshot_date, COUNT(*) AS n
FROM analytics.fct_account_daily
GROUP BY account_id, snapshot_date
HAVING COUNT(*) > 1;

If you only add one test, add this one.

Not null: on the columns that matter

Don't test every column. Test the ones that would quietly break a calculation or a filter: keys, dates, status fields, anything used in a WHERE or GROUP BY downstream.

SELECT *
FROM analytics.fct_account_daily
WHERE account_id IS NULL
   OR snapshot_date IS NULL
   OR service_status IS NULL;

A null region won't crash anything. It just falls out of every regional breakdown, so the regions no longer add up to the total and nobody can say why.

Relationships: nothing falls out of the join

An inner join drops rows that have no match, and it doesn't tell you. Check that every foreign key has somewhere to land:

-- Facts whose account doesn't exist in the dimension
SELECT f.account_id, COUNT(*) AS orphan_rows
FROM analytics.fct_account_daily f
LEFT JOIN analytics.dim_account d
  ON d.account_id = f.account_id
WHERE d.account_id IS NULL
GROUP BY f.account_id;

Accepted values: no surprise categories

Upstream systems add new status codes without asking you. When 'Active' shows up next to 'active', or a new 'suspended_pending' appears, every filter written as = 'active' is silently wrong.

SELECT service_status, COUNT(*) AS n
FROM analytics.fct_account_daily
WHERE service_status NOT IN ('active', 'suspended', 'cancelled')
GROUP BY service_status;

Freshness: the data actually arrived

The most common data incident is boring: the load didn't run, and the dashboard happily shows yesterday's numbers as today's.

-- Fail if the newest snapshot is more than a day old
SELECT MAX(snapshot_date) AS latest
FROM analytics.fct_account_daily
HAVING MAX(snapshot_date) < CURRENT_DATE - 1;

Date arithmetic varies by warehouse (DATEADD, INTERVAL, DATE_SUB), so adjust the last line for your dialect. The idea carries over.

Volume and reconciliation: the totals make sense

Every test so far checks individual rows. This one checks whether the table as a whole looks right. There are two versions worth having.

Reconciliation compares your modelled table to its source. If the warehouse says revenue was one number and the billing system says another, you want to know before finance does:

WITH source AS (
  SELECT SUM(amount) AS total
  FROM raw.billing_invoices
  WHERE invoice_date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30'
),
modelled AS (
  SELECT SUM(revenue) AS total
  FROM analytics.fct_revenue_monthly
  WHERE revenue_month = DATE '2026-11-01'
)
SELECT s.total AS source_total, m.total AS modelled_total
FROM source s CROSS JOIN modelled m
WHERE ABS(s.total - m.total) > 0.005 * s.total; -- allow 0.5% for known adjustments

Volume checks catch partial loads: a file that arrived with half its rows. Compare today's row count to recent history:

WITH daily AS (
  SELECT load_date, COUNT(*) AS n
  FROM raw.usage_events
  WHERE load_date >= CURRENT_DATE - 28
  GROUP BY load_date
),
history AS (
  SELECT AVG(n) AS mean_n, STDDEV(n) AS sd_n
  FROM daily
  WHERE load_date < CURRENT_DATE
)
SELECT d.load_date, d.n, h.mean_n
FROM daily d CROSS JOIN history h
WHERE d.load_date = CURRENT_DATE
  AND ABS(d.n - h.mean_n) > 3 * h.sd_n;

Two caveats. First, if today's data is missing entirely, there's no row for today and this test passes. That's why it needs the freshness check beside it. Second, if your data has a strong weekly pattern, compare against the same weekday in previous weeks instead, or every Monday will set it off.

Running them

If you use dbt, most of these are one-liners in a YAML file (unique, not_null, relationships, accepted_values) plus a source freshness config, and you write the last two as custom tests.

If you don't, you need very little: a folder of .sql files and a runner that fails when any of them returns rows.

from pathlib import Path
 
 
def run_data_tests(folder, run_sql):
    """run_sql(sql) -> list of rows. Each .sql file should return only failing rows."""
    failed = []
    for test in sorted(Path(folder).glob("*.sql")):
        rows = run_sql(test.read_text())
        status = "FAIL" if rows else "ok"
        print(f"{status:4}  {test.stem}  ({len(rows)} rows)")
        if rows:
            failed.append(test.stem)
    if failed:
        raise SystemExit(f"{len(failed)} data test(s) failed: {', '.join(failed)}")

Run it after every load, before the dashboards refresh. Then decide in advance what a failure does. A test that fails into a channel nobody reads is just a log file. The useful options are blocking the refresh, or putting a visible "data may be incomplete" banner on the report.

Where to start

Don't try to test everything at once. Pick the one table behind your most-viewed report, or the one you're about to hand to an AI assistant, and give it a uniqueness test, a freshness test, and a reconciliation against its source.

Those three cover the most common ways data goes wrong. More importantly, they turn "can I trust this number?" from a feeling into a check that either passed this morning or didn't.