
DAX Variables and IF: Effects on Branch Evaluation
DAX variables can reduce repeated work, but placing them outside IF can also add work. Share a variable when the same value is needed in the same context. Keep branch-only calculations inside their branch, and use IF.EAGER when both branches should run.
The difference is scope - not just shorter code. Ordinary IF can use strict or eager evaluation, so variable placement alone does not prove which calculations run.
Quick Comparison
| Pattern | Main use | What to check |
|---|---|---|
| Repeated expressions | Keep short logic direct | Repeated text may already share work |
| Shared variable | Reuse one result in the same context | Results match; measured work falls |
| Outer branch-only variable | Name a result before IF |
Unused branch work may increase |
| Branch-local variable | Keep a calculation where it is used | Skipping unused work is not guaranteed |
| Direct branch expressions | Keep one-off calculations short | Evaluation still depends on the plan |
IF.EAGER |
Explicitly evaluate both branches | Shared work offsets the added branch cost |
One cited SQLBI example reduced a physical plan from 216 rows to 126 - but that does not establish an elapsed-time gain. Before keeping a rewrite, check blanks, detail rows, and totals. Then compare query plans and cold- and warm-cache timings in DAX Studio.
DAX Variables and IF: Scope vs. Branch Evaluation
Evaluation of variables in DAX
sbb-itb-61a6e59
1. Repeating an Expression
Use this measure as the baseline. It checks whether prior-year sales are positive and returns that amount if they are. Otherwise, it returns blank.
Prior-Year Sales Check := IF ( CALCULATE ( [Sales Amount], DATEADD ( 'Date'[Date], -1, YEAR ) ) > 0, CALCULATE ( [Sales Amount], DATEADD ( 'Date'[Date], -1, YEAR ) ), BLANK () )
Branch Execution
Ordinary IF evaluates the condition first and usually runs only the branch it needs. The question is whether repeating the expression changes the execution plan - or just makes the formula harder to read.
Engine Work
Two copies don't necessarily mean two calculations. The optimizer may share the work. Check DAX Studio’s Server Timings and query plan before attributing any performance gain to a variable.
Context and Correctness
This measure assumes a contiguous, marked Date table. Both calls apply the same one-year shift in the same filter context, keeping product and region filters in place. Before comparing performance, verify the results for positive, zero, and missing prior-year sales, as well as totals.
Readability and Reuse
The main cost is duplicated logic: a change to the date logic requires two matching edits. Naming the shared result PriorYearSales removes that duplication. The next rewrite stores the shared result in a variable and tests whether branch evaluation changes.
2. Sharing a Result with a Variable
Define PriorYearSales once, then reuse it in both the test and the result.
Prior-Year Sales Check := VAR PriorYearSales = CALCULATE ( [Sales Amount], DATEADD ( 'Date'[Date], -1, YEAR ) ) RETURN IF ( PriorYearSales > 0, PriorYearSales, BLANK () )
Branch Execution
The variable is evaluated once, and the true branch reuses that value. Using a variable does not force both IF branches to run or change which branch is selected.
Engine Work
A referenced variable is evaluated at most once per measure evaluation. This can remove duplicate formula work, but it doesn't guarantee fewer storage-engine requests or a faster query.
Context and Correctness
PriorYearSales is computed once in the CALCULATE filter context, including the one-year date shift. Every reference to it within this measure evaluation uses that same value.
Readability and Reuse
To debug the measure, return PriorYearSales directly. Check the shifted value, then restore the IF.
Next, move the variable outside the IF test and compare how that changes evaluation.
3. Defining Variables Before IF
This version tests whether moving an expression outside IF changes how it's evaluated. Only the true branch uses Margin, so defining it outside IF provides no reuse and may change evaluation.
Margin Outer Variable := VAR Margin = [Sales Amount] - [Total Cost] RETURN IF ( [Sales Amount] > 0, Margin, BLANK () )
Branch Execution
Defining Margin before IF does not guarantee lazy evaluation. The engine may compute it in the outer context before checking the condition.
Engine Work
Moving Margin outside IF can also block branch-specific optimization, without adding any reuse.
Context and Correctness
A variable is evaluated in the filter context where it's defined. Inside an IF branch, the engine can use branch-specific filter context. Outside IF, that context may not apply, which can affect both performance and results.
When moving a context-sensitive calculation, compare detail rows, subtotals, and grand totals using representative filters.
Readability and Reuse
Use an outer variable only when its value feeds the condition or both branches. Keep calculations used by just one branch inside that branch.
Next, move the same calculation inside the branch and compare the plan.
4. Defining Variables Inside IF Branches
A branch-local variable keeps a calculation inside the path that uses it. Unlike an outer variable, this placement can help the engine skip unused work.
Branch Execution
Keep branch-only logic inside its branch. Each result argument can define its own VAR … RETURN block:
IF ( [Condition], VAR _true = [Calc1] RETURN _true, VAR _false = [Calc2] RETURN _false )
Each variable is visible only within its own branch.
Engine Work
Branch-local variables can preserve short-circuiting, but they don't guarantee it. The engine can still choose strict or eager evaluation. Check Server Timings and query plans in DAX Studio, looking at both storage-engine scans and formula-engine work.
Context and Correctness
A branch-local variable inherits the branch’s filter context. Moving it outside the branch can change that context, when the calculation runs, and its results. Keep CALCULATE inside the branch when it relies on branch-specific filters.
Readability and Reuse
Use local variables when a branch reuses a calculation or needs a named intermediate result. If a calculation appears only once, writing the expression directly may be cleaner.
5. Using Expressions Directly in IF
Branch Execution
This version uses the same IF logic without variables. Put expressions directly in IF when each branch needs a short, one-off calculation.
Conditional Sales = IF ( [Sales Amount] > 100000, [Sales Amount] * 0.95, [Sales Amount] * 1.05 )
Engine Work
Repeating [Sales Amount] does not prove that the engine evaluates it each time; it may reuse earlier work. A shared VAR Sales = [Sales Amount] makes that reuse explicit. It’s worth benchmarking when [Sales Amount] is costly to calculate.
Context and Correctness
An inline expression matches a variable only when both evaluate in the same context. Switching from a variable to a direct measure reference can change detail-row results or totals when filter context or context transition matters.
The difference: the inline measure recalculates in the current filter context, while the variable returns the value stored when it was defined. Check detail rows and totals before treating the two forms as interchangeable.
Readability and Reuse
Direct expressions make short rules easy to scan. Variables help when a name or repeated use makes the code clearer. Here, sales appears in the condition and both outcomes, so a shared variable is cleaner - but it doesn’t guarantee better performance.
If you need to change branch evaluation itself, the next pattern is IF.EAGER.
6. Evaluating Both Branches with IF.EAGER
Branch Execution
IF.EAGER evaluates both branches, then returns the selected result. Ordinary IF may skip the unused branch, depending on the plan and context.
You can request eager evaluation directly with IF.EAGER or define both branch results in variables before IF. The difference is how you express the execution strategy.
Margin or Forecast := IF.EAGER ( [Total Sales] > 1000000, [Gross Margin], [Forecast Amount] )
Microsoft documents the same execution pattern for this variable rewrite. Here, variable placement - not IF syntax - produces the eager plan.
Margin or Forecast - Variables := VAR MarginValue = [Gross Margin] VAR ForecastValue = [Forecast Amount] RETURN IF ( [Total Sales] > 1000000, MarginValue, ForecastValue )
Engine Work
Evaluating both branches doesn't always double the cost. Shared work can make eager evaluation cheaper, while unrelated, expensive branches can make it slower.
Compare equivalent versions in DAX Studio using Server Timings and query plans. Keep filters and cache conditions the same, then check formula-engine duration, storage-engine query count, and total execution time.
Context and Correctness
These rewrites return the same result when the measures are deterministic and the condition stays unchanged.
Readability and Reuse
Choose IF.EAGER when you want explicit eager evaluation and measurements support that choice. Use variables to reuse results or give them clearer names - not as a default performance shortcut.
The next section compares execution, cost, and correctness across the rewrites.
Comparing Execution, Cost, and Correctness
A rewrite can change how a query runs, what it costs, or what it returns. Check each effect separately.
Branch Execution: Strict vs. Eager Evaluation
Logical intent and physical execution are different. Where you define a variable doesn’t prove when the engine runs its calculation.
| Pattern | Execution behavior | Verification |
|---|---|---|
Ordinary IF |
Optimizer-dependent strict or eager plan | Identify the chosen strategy |
Variables defined before IF |
Can expose shared work across branches | Look for work beyond the selected branch |
| Branch-local variables | Express conditional dependence but don’t guarantee short-circuiting | Check whether unused work remains |
IF.EAGER |
Explicitly evaluates both branch expressions | Check the cost of both branches |
Compare Server Timings, storage-engine queries, and query plans for both condition outcomes. Microsoft documents IF.EAGER as conceptually equivalent to defining both branch results before RETURN, then selecting one with IF.
The execution strategy tells you how the work runs. Next, check whether the rewrite reduces that work.
Engine Work: Repeated Expressions vs. Shared Results
Fewer expressions don’t always mean less work. The optimizer may already share repeated calculations. Moving branch-only work outside its branch can add cost. Eager evaluation, meanwhile, can win when it batches shared work efficiently.
Selective conditions may favor strict evaluation. Mixed cells and high-cardinality groupings can change that tradeoff. Treat these as ideas to test, not performance promises.
| Pattern | Potential engine effect | Favorable conditions |
|---|---|---|
| Repeated expressions | Repeated text may share work | Direct code stays clear |
| Shared result | Can avoid repeated calculation | The same value is needed in the same context |
| Hoisted branch-only result | May add unnecessary work | Measurements show a gain |
| Branch-local result | Can avoid unused work | Calculation is needed only in one branch |
| Explicit eager evaluation | Can batch shared scans but adds branch work | Measured savings outweigh added work |
Test rewrites on the same visual, with the same filters, groupings, and engine version. Then compare cold-cache and warm-cache runs in DAX Studio.
Lower cost isn’t enough if the result changes. Variable scope needs a separate check.
Correctness: Variable Definition Context
These measures show the difference between storing [Sales] before a later filter and calculating it inside that filter.
IncorrectForRedSales = VAR S = [Sales] RETURN CALCULATE ( S, 'Product'[Color] = "Red" )
RedSales = CALCULATE ( [Sales], 'Product'[Color] = "Red" )
| Definition placement | Effect on results | Required checks |
|---|---|---|
Before later CALCULATE |
Scalar keeps its definition-context value; later filters don’t recalculate it | Intended filter, blanks, types, totals |
Calculation inside CALCULATE |
Measure receives the specified filter | Compare filtered results |
| Outside an iterator | One outer-context scalar is reused for every row | Detail rows and totals |
| Inside an iterator | Measure references receive row-derived filters through context transition | Per-row values and totals |
The same scope rule applies to iterators and branch logic: placement can change which context supplies the value.
Readability and Reuse: Variable Scope
Variables hold scoped results. They aren’t caches across visual cells or queries.
| Expression role | Recommended placement | Required verification |
|---|---|---|
| Repeated in the same context | Shared variable | Equivalent contexts and measured reuse |
| Condition-only | Direct condition or named variable for clarity | Condition values and BLANK() behavior |
| Branch-only | Inside that branch | Equivalent results and unused work |
| Shared across branches | Shared variable when the definition context matches | Both outcomes, mixed cells, and totals |
Strengths and Limits of Each Rewrite
These rewrites overlap, but they differ in what they share and when the engine evaluates it. Placing work inside or outside IF branches affects branch evaluation, context, and measured cost.
The point isn't which rewrite looks simplest. It's which one changes evaluation scope and cost.
| Pattern | Strengths | Limits | Suitable uses |
|---|---|---|---|
| Repeated expressions | Provides a clear baseline | May duplicate work | Short calculations; correctness baseline |
| Shared variable | Evaluates a result at most once in its defining context, then reuses it | References must need that same value | Repeated calculations in the same context |
Variables before IF |
Makes common dependencies explicit | May move branch-only work into the outer context | Work that branches actually share, or gains confirmed by measurement |
| Branch-local variables | Keeps work within one branch | Cannot share work across branches; does not guarantee short-circuit evaluation | Complex, branch-specific calculations |
Direct expressions inside IF |
Keeps one-off work in its branch | Repetition can make code harder to read; evaluation still depends on the optimizer | Short, readable branch expressions |
IF.EAGER |
Explicitly requests eager evaluation | Incurs the cost of both outcomes | Eager strategies tested through measurement |
In one SQLBI example, replacing repeated measure references cut the physical plan from 216 rows to 126 and used two storage-engine requests.
This reports an observed plan change - not a guaranteed speedup or a percentage reduction in elapsed time.
When comparing equivalent rewrites, check both the plan and timings: does the rewrite preserve results while reducing measured work?
Conclusion: Share Repeated Work, Keep Branch-Only Work Local
The rewrites above point to one rule: share repeated work, keep branch-only work local, and use IF.EAGER deliberately. Variables and standard IF syntax don’t control the physical plan.
Before keeping a rewrite, check totals, subtotals, blanks, and both condition outcomes. Then test the same visual with representative filters and data volumes. Compare cold- and warm-cache runs, checking formula-engine time, storage-engine requests, CPU, and duration.
Use this matrix to match your rewrite to the plan and results you observed.
| Expression dependency | Rewrite choice | Evidence needed to retain it |
|---|---|---|
| Shared result in one context | Share one variable before IF |
Confirm that the context and results match. |
| Branch-only work | Keep its variable inside that branch | Check plans for unused branch work. |
| Changed filter context | Evaluate within the required context | Verify filtered results and context transitions. |
| Deliberate eager evaluation | Test IF.EAGER |
Confirm both expressions are safe. Keep it only if CPU, duration, and request counts justify it. |
FAQs
How can I tell which IF branches actually ran?
DAX has no built-in execution log or debugger that visually shows which IF branches ran. Instead, use performance profiling tools to inspect evaluation plans and determine whether specific calculations were triggered.
This helps explain how placing variables inside or outside IF branches affects evaluation - and why variables don’t always reduce calculation costs.
Why did moving a variable change my totals?
The information provided doesn’t explain why moving a variable changed your totals. Placing variables inside or outside IF branches can affect evaluation plans, but that alone doesn’t explain the change in your totals.
When can evaluating both branches be faster?
The provided search results don’t cover DAX variables, IF branch evaluation, or measure rewrites. They therefore don’t explain when evaluating both branches might be faster.