0
0
dbtdata~10 mins

if/else logic in models in dbt - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - if/else logic in models
Start
Evaluate condition
Execute IF block
Execute ELSE block
Continue with rest of model
The model checks a condition. If true, it runs the IF part; otherwise, it runs the ELSE part, then continues.
Execution Sample
dbt
select
  case
    when sales > 100 then 'High'
    else 'Low'
  end as sales_category
from sales_data
This SQL code classifies sales as 'High' if sales are over 100, otherwise 'Low'.
Execution Table
RowsalesCondition (sales > 100)Branch TakenOutput sales_category
1150TrueIF'High'
290FalseELSE'Low'
3100FalseELSE'Low'
4200TrueIF'High'
550FalseELSE'Low'
💡 All rows processed; condition evaluated for each row to assign category.
Variable Tracker
VariableRow 1Row 2Row 3Row 4Row 5
sales1509010020050
Condition (sales > 100)TrueFalseFalseTrueFalse
sales_category'High''Low''Low''High''Low'
Key Moments - 2 Insights
Why does sales = 100 result in 'Low' and not 'High'?
Because the condition is sales > 100, which means strictly greater than 100. At 100, the condition is False, so ELSE branch runs (see execution_table row 3).
What happens if the condition is True for a row?
The IF block runs, assigning 'High' to sales_category (see execution_table rows 1 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is sales_category for row 2?
A'High'
B'Low'
CNULL
D'Medium'
💡 Hint
Check row 2 in execution_table under 'Output sales_category'
At which row does the condition sales > 100 become False for the first time?
ARow 1
BRow 3
CRow 2
DRow 5
💡 Hint
Look at 'Condition (sales > 100)' column in execution_table
If the condition changed to sales >= 100, what would sales_category be for row 3?
A'High'
B'Low'
CNULL
D'Medium'
💡 Hint
Consider how changing > to >= affects condition for sales = 100 in variable_tracker
Concept Snapshot
if/else logic in dbt models uses SQL CASE statements.
Syntax: CASE WHEN condition THEN result ELSE other_result END.
Evaluates condition row-by-row.
Runs THEN part if True, ELSE part if False.
Useful for categorizing or branching logic in models.
Full Transcript
In dbt models, if/else logic is done using SQL CASE statements. The model checks a condition for each row. If the condition is true, it runs the THEN part; otherwise, it runs the ELSE part. For example, classifying sales as 'High' if sales are greater than 100, else 'Low'. The execution table shows each row's sales value, condition result, branch taken, and output category. Note that sales exactly 100 is not greater than 100, so it falls into the ELSE branch. This logic helps create categories or decisions inside your data models.