Data tests
A model can build without errors and still be wrong: duplicate ids, missing values, orphan keys. dbt data tests catch those after every build. This lesson shows the built-in tests, custom ones, and how to set severity.
Pipelines in production · dbt · Bronze · Building models, lesson 4 of 4
On this page
Read first: ref() and the DAG (skip if you know it)
In plain words first
A quality inspector does not check every product by hand; they look for the faulty ones. "Show me every bottle with no cap." If the answer is none, the batch passes.
A dbt data test is that question as a SELECT: it returns the rows breaking a rule, and zero rows means pass.
A test is a query for bad rows
Every dbt data test compiles to a SELECT that returns the rows breaking the rule. Zero rows: pass. Any rows: fail (or warn). That single idea covers everything from not_null to complex business rules.
models:
- name: fct_invoices
columns:
- name: invoice_id
data_tests:
- unique
- not_null
- name: status
data_tests:
- accepted_values:
values: ['draft', 'open', 'paid', 'void']
- name: account_id
data_tests:
- relationships:
to: ref('dim_accounts')
field: account_id
select invoice_id, count(*) as n_records from analytics.dbt_alice.fct_invoices where invoice_id is not null group by invoice_id having count(*) > 1
The built-in generic tests
| Test | Fails when | Note |
|---|---|---|
| unique | A value appears more than once | Nulls are ignored: pair it with not_null for a primary key. |
| not_null | A value is null | |
| accepted_values | A value is not in the list | Nulls pass; add not_null if they should not. |
| relationships | A value has no match in the other modelmodel: A SELECT statement in a .sql file. dbt runs it and saves the result in the warehouse as a table or view named after the file. Learn more → | Orphan check, like a foreign key. Nulls pass. |
The YAML key is data_tests: since dbt 1.8 (the older tests: still works). Tests on a sourcesource: A raw table loaded by another tool, declared in YAML so models can select from it with source() and dbt can test it and check its freshness. Learn more → column are declared the same way in the source YAML, and run against raw data before staging.
Singular tests
For a rule that only one model needs, write the failing-rows query yourself in tests/. Any SQL works, as long as rows mean failure.
-- An invoice's total must equal the sum of its lines (to the cent). with line_totals as ( select invoice_id, sum(quantity * unit_price) as lines_total from {{ ref('stg_invoice_lines') }} group by invoice_id ) select i.invoice_id, i.total, l.lines_total from {{ ref('fct_invoices') }} as i join line_totals as l on l.invoice_id = i.invoice_id where abs(i.total - l.lines_total) >= 0.01
A rule you need on many models becomes a custom generic test, written like a macromacro: A reusable piece of Jinja, like a function that returns SQL. You call it with {{ my_macro(...) }}. Learn more → (see Macros and custom generic tests).
Making tests practical
- name: email
data_tests:
- not_null:
config:
severity: error
warn_if: ">0"
error_if: ">100" # a few missing emails warn; many fail the run
where: "created_at >= '2024-01-01'" # legacy rows are exempt
store_failures: true # save failing rows to a table for debugging
- severity: warn reports without failing the run, for rules you are still learning about.
- warn_if / error_if use the number of failing rows, so a known small problem does not page anyone.
- where limits the test to part of the table.
- store_failures writes the failing rows to a table in an
_dbt_test__auditschema, so you can query them instead of re-running the SQL.
Which tests to write
- 1Every model's grain: unique and not_null on its primary key. This one test catches most join fan-out bugs.
- 2Foreign keys in marts: relationships, so orphan facts are noticed.
- 3Status and type columns: accepted_values, so a new value from the source is noticed before it falls into an "other" bucket.
- 4Business rules that have bitten you before: singular tests.
Common mistakes
- unique without not_null on a key — unique ignores nulls, so a key column full of nulls passes.
- Testing everything with severity error — Noisy failures get ignored. Use warn and thresholds for soft rules.
- Writing a singular test that returns a count — A query returning one row with count 0 still returns a row, so it fails. Return the bad rows themselves.
Key takeaways
- A dbt test is a query for failing rows; no rows means pass.
- unique, not_null, accepted_values and relationships cover most needs; nulls pass all but not_null.
- Singular tests are one-off SQL files in tests/.
- Severity, thresholds, where and store_failures keep tests useful instead of noisy.
Interview prep
THE QUESTION
"How do dbt tests work, and which ones do you put on every model?"
tests/. On every model I test the grain: unique and not_null on the primary key, which catches fan-out. On marts I add relationships for foreign keys and accepted_values for statuses. Severity, warn_if/error_if thresholds, where and store_failures keep them actionable, and dbt build runs them right after each model so failures stop downstream models.Avoid: "tests check that the model runs". A dbt test is a query for rows that break a rule in the built data.
Follow-ups · answer out loud, then open
Follow-up"Why do unique tests pass on a column full of nulls?"
Scenario"A not_null test fails every night on 12 old rows nobody can fix. What do you do?"
where to exempt the legacy range, or warn_if: ">0" with error_if above the known count, and store_failures to keep the rows visible. Fix the data if it is ever possible.Trap"A singular test that returns select count(*) from bad_rows is fine."
Check yourself
3 questionsA singular test returns 3 rows. What happens?
Show the answer
It fails (or warns) with 3 failures. Returned rows are failures.
A primary key column has two nulls and no duplicates. Which test catches it?
Show the answer
not_null. unique ignores nulls; not_null does not.
What does store_failures: true do?
Show the answer
Saves the failing rows to a table. Failing rows are written to an audit schema for inspection.
Practise this
Problems that use this, graded on hidden tests
- Write the Tests for an Orders ModelData tests Easy
- Catch Orphaned and Invalid PaymentsData tests Medium
- Data Test: Refunds Larger Than the OrderData tests Easy
Keep going
Up next · new module: Jinja and reuse · 5 min readJinja in dbt
Expressions, statements, loops and set: write SQL that writes SQL, and read what it compiles to.
Related lessons
Macros and custom generic testsdbt · 5 min read
Unit testsdbt · 5 min read
Contracts, versions and access
Previous: Materializations
Primary sources: Add data tests to your DAG · Test configs