Skip to content
Bronze 5 min read · Tests 3 practice problems ↓

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

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.

YAML · models/marts/_marts__models.yml
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
dbt · What unique compiles to
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

TestFails whenNote
uniqueA value appears more than onceNulls are ignored: pair it with not_null for a primary key.
not_nullA value is null
accepted_valuesA value is not in the listNulls pass; add not_null if they should not.
relationshipsA 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.

dbt · tests/assert_invoice_total_matches_lines.sql
-- 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

YAML · models/marts/_marts__models.yml
      - 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__audit schema, so you can query them instead of re-running the SQL.

Which tests to write

  1. 1
    Every model's grain: unique and not_null on its primary key. This one test catches most join fan-out bugs.
  2. 2
    Foreign keys in marts: relationships, so orphan facts are noticed.
  3. 3
    Status and type columns: accepted_values, so a new value from the source is noticed before it falls into an "other" bucket.
  4. 4
    Business rules that have bitten you before: singular tests.
Note: Data tests check the data that was built. To check a model's logic on fixed inputs before building it, dbt 1.8 added unit tests (see Unit 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?"

A test compiles to a query that returns failing rows; zero rows passes. Generic tests (unique, not_null, accepted_values, relationships, plus custom and package ones) are declared in YAML on columns; singular tests are SQL files in 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?"
The unique test ignores nulls (and SQL grouping treats them specially), so it only catches repeated non-null values. A primary key needs both unique and not_null.
Scenario"A not_null test fails every night on 12 old rows nobody can fix. What do you do?"
Do not delete the test. Use 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."
It always returns one row, so it always fails. Tests must return the failing rows themselves.

Check yourself

3 questions

A 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

See all 6 problems →

Keep going

Up next · new module: Jinja and reuse · 5 min read
Jinja in dbt
Expressions, statements, loops and set: write SQL that writes SQL, and read what it compiles to.

Related lessons

Previous: Materializations

Primary sources: Add data tests to your DAG · Test configs