How to Use If Statements in Jinja for dbt Models
In dbt, you use
{% if condition %} ... {% endif %} to run SQL code conditionally inside Jinja templates. This lets you change your SQL based on variables or environment settings dynamically.Syntax
The if statement in Jinja for dbt controls conditional logic. It starts with {% if condition %}, runs the code inside if the condition is true, and ends with {% endif %}. You can add {% elif %} and {% else %} for multiple conditions.
{% if condition %}: Checks if the condition is true.- Code inside runs only if true.
{% elif other_condition %}: Optional, checks another condition if first is false.{% else %}: Optional, runs if all conditions are false.{% endif %}: Ends the if block.
jinja
{% if condition %}
-- SQL code here
{% elif other_condition %}
-- alternative SQL code
{% else %}
-- fallback SQL code
{% endif %}Example
This example shows how to use an if statement in a dbt model to choose a filter based on a variable is_active. If is_active is true, it filters active users; otherwise, it returns all users.
jinja
{% set is_active = true %}
select *
from users
where 1=1
{% if is_active %}
and status = 'active'
{% endif %}Output
select *
from users
where 1=1
and status = 'active'
Common Pitfalls
Common mistakes when using if in Jinja for dbt include:
- Forgetting to close the
ifblock with{% endif %}, which causes syntax errors. - Using Python-style
ifsyntax without Jinja tags, which won't work. - Not properly setting or passing variables before using them in conditions.
- Trying to use
ifinside raw SQL without Jinja tags, which dbt cannot interpret.
Example of wrong and right usage:
jinja
-- Wrong (missing {% endif %})
{% if is_active %}
select * from users where status = 'active'
-- Right
{% if is_active %}
select * from users where status = 'active'
{% endif %}Quick Reference
| Syntax | Description |
|---|---|
| {% if condition %} ... {% endif %} | Run code if condition is true |
| {% if condition %} ... {% else %} ... {% endif %} | Run code if condition true, else run alternative |
| {% if condition %} ... {% elif other_condition %} ... {% else %} ... {% endif %} | Multiple conditions with else fallback |
| {{ variable }} | Print variable value |
| {% set var = value %} | Set a variable for use in conditions |
Key Takeaways
Use {% if condition %} ... {% endif %} to add conditional logic in dbt Jinja templates.
Always close your if blocks with {% endif %} to avoid errors.
You can combine {% elif %} and {% else %} for multiple conditions.
Set variables with {% set %} before using them in if statements.
Jinja if statements let you write flexible, dynamic SQL in dbt models.