if/else logic in models in dbt - Time & Space Complexity
We want to see how using if/else logic in dbt models affects how long the code takes to run.
Specifically, we ask: does adding if/else slow down the model as data grows?
Analyze the time complexity of the following code snippet.
select
id,
case
when amount > 100 then 'high'
else 'low'
end as amount_category
from {{ ref('sales_data') }}
This code classifies each row's amount as 'high' or 'low' using if/else logic inside a dbt model.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The case (if/else) check runs once for each row in the input table.
- How many times: Exactly once per row, so as many times as there are rows.
Each row is checked once, so if the data doubles, the work doubles too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of rows.
[X] Wrong: "If I add if/else, the model will run much slower because it adds extra steps."
[OK] Correct: The if/else check happens once per row, just like reading the row itself, so it does not add extra loops or multiply work.
Understanding how simple conditional logic scales helps you explain model performance clearly and confidently.
"What if we added a nested if/else inside the first one? How would the time complexity change?"