0
0
dbtdata~10 mins

Variables and control flow in dbt - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variables and control flow
Start
Set Variable
Check Condition
Execute Block
Update Variable or End
Back to Check or End
This flow shows how dbt sets variables, checks conditions, executes code blocks based on conditions, and updates variables or ends.
Execution Sample
dbt
{% set my_var = 0 %}

{% if my_var < 2 %}
  {{ log('Variable is less than 2') }}
{% endif %}
This dbt snippet sets a variable and uses an if condition to log a message if the variable is less than 2.
Execution Table
StepActionVariable 'my_var'Condition 'my_var < 2'Branch TakenOutput
1Initialize variable 'my_var'0N/AN/AVariable set to 0
2Evaluate condition 'my_var < 2'0TrueYesLog message: 'Variable is less than 2'
3End of control flow0N/AN/AExecution stops
💡 Reached end of code after condition check and logging
Variable Tracker
VariableStartAfter Step 1After Step 2Final
my_varundefined000
Key Moments - 2 Insights
Why does the condition 'my_var < 2' evaluate to True when 'my_var' is 0?
Because 0 is less than 2, the condition is True as shown in execution_table row 2, so the code inside the if block runs.
What happens if the variable 'my_var' was 3 instead of 0?
The condition 'my_var < 2' would be False, so the branch taken would be No, skipping the log message. This is shown by the condition check logic in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'my_var' at Step 2?
A2
B0
C1
Dundefined
💡 Hint
Check the 'Variable my_var' column at Step 2 in the execution_table.
At which step does the condition 'my_var < 2' get evaluated?
AStep 2
BStep 1
CStep 3
DNo step
💡 Hint
Look at the 'Condition' column in the execution_table to find when it is evaluated.
If 'my_var' was set to 3, what would happen at Step 2?
ACondition True, log message printed
BError occurs
CCondition False, log message skipped
DVariable changes to 0
💡 Hint
Refer to key_moments explanation about variable values and condition outcomes.
Concept Snapshot
dbt variables store values used in control flow.
Use {% if name < value %} to check conditions.
Code inside if runs only if condition is True.
Variables do not change unless explicitly updated.
Control flow ends after last statement.
Full Transcript
In dbt, variables hold values that control the flow of code. We start by setting a variable, like 'my_var' to 0. Then we check if 'my_var' is less than 2. Since 0 is less than 2, the condition is True, so the code inside the if block runs and logs a message. If the variable was 3, the condition would be False and the code inside the if block would be skipped. Variables keep their values unless changed. The flow ends after the last statement.