0
0
DbtHow-ToBeginner ยท 3 min read

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 if block with {% endif %}, which causes syntax errors.
  • Using Python-style if syntax without Jinja tags, which won't work.
  • Not properly setting or passing variables before using them in conditions.
  • Trying to use if inside 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

SyntaxDescription
{% 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.