dbt Series #1 Building and Testing Simple Filter Models in dbt(unit test)
When you're learning dbt, it helps to start with something dead simple — filtering a table into two halves. That's exactly what this little project does: take a base model called one (just a list of integers 1 through 5), and split it into two derived models, odd and even.
odd.sql takes everything from one and keeps only the rows where the value isn't evenly divisible by 2:
with cte as (
select
*
from
{{ ref('one') }}
where
one%2 != 0
)
select
*
from
cte
even.sql does the mirror image — it keeps only the rows where the value is evenly divisible by 2
with cte as (
select
*
from
{{ ref('one') }}
where
one%2 = 0
)
select
*
from
cte;
Both models follow the same pattern wrap the source reference in a CTE, apply a modulo filter, and select back out. It's not fancy, but it's a clean, readable template you can build on for more complex filtering logic later — the CTE gives you a natural place to add more transformations without rewriting the whole query.
Why Bother With Unit Tests for Something This Simple?
It's tempting to skip testing on "toy" models like this, but that's exactly why they're a great place to practice testing. dbt's unit tests let you feed in fake, hardcoded input rows — no need to touch your real warehouse — and assert exactly what should come out the other side. If your filter logic ever gets flipped, fat-fingered, or refactored, the test catches it in seconds instead of you noticing weird numbers in a downstream dashboard three weeks later.
Here's what that looks like for both models unit test.
unit_tests:
- name: test_only_odd
model: odd
given:
- input: ref('one')
format: dict
rows:
- {one: 1}
- {one: 2}
- {one: 3}
- {one: 4}
expect:
rows:
- {one: 1}
- {one: 3}
- name: test_only_even
model: even
given:
- input: ref('one')
format: dict
rows:
- {one: 1}
- {one: 2}
- {one: 3}
- {one: 4}
expect:
rows:
- {one: 2}
- {one: 4}
Each test feeds the same four rows (1, 2, 3, 4) into the model under test, and asserts the exact rows that should come back out. The even model should keep 2 and 4; the odd model should keep 1 and 3. Simple, deterministic, and fast — the whole point of unit testing at this layer.
dbt test -s "test_type:unit"
Thank you.
Comments
Join the discussionNo comments yet. Be the first to comment.

