DAX Power BI: VAR — Create Variables

Andrei Khaidarov, Microsoft MVP, PhD
Power Platform
Published in
3 min readJun 13, 2023

--

Before learning complex functions in DAX it is necessary to become familiar with the creation of variables. These variables are created so that we can simplify the creation of complex functions for ourselves.

Variables:

Simplify the perception of complex code
Reduce code execution time
Allow you to control the context of a string
In the example below, in addition to the usual columns, we have a Profit column created with DAX. There we calculate profits across all rows in the table.

Now modernize this code by adding variables to it. To do this, at the very beginning of our code we write the service word VAR. After the service word, write the name of the variable, and after the name, put an equal sign and then assign a value to this variable.

We then write the RETURN function word. This special word shows that we are done enumerating all variables. The RETURN word is followed by the main code of our computable column.

The values of the created column remain the same, which means that the code is fully working.

Now let’s complicate this code even further by adding one more variable to this code.

At the same time, the values in the column did not change either.

We see that by creating variables we can improve the visual understanding of various complex measures. To further improve the code, you can use comments. They start with two dashes. This text is not visible to DAX, and will help the user better understand what a particular line or function does.

Let’s summarize a little bit about variables.

First, the word VAR is written in front of each variable. Next is the name of the variable. This is written only in Latin letters. After the variable name, the equal sign and after it the code of the variable itself.

After you have written all the variables, you must write the word RETURN, which means that the variable declaration is complete, and then you go to the main program code.

Why do we need variables in DAX?

They allow you to simplify the complex DAX code visually, allow to reduce the time of calculation of complex code (this is done at the expense of the fact that the program will not have to calculate the same expression several times, it is enough to calculate the value for one variable, and then use the value obtained), and finally, variables allow you to remember the context of the string in which the variable was calculated.

Another point worth noting is why variables are called variables?

In this programming language, unlike other languages, the name “variables” can be called a bit of a stretch, because it does not make the same sense as in other programming languages.

--

--

Andrei Khaidarov, Microsoft MVP, PhD
Power Platform

🎓 Microsoft Data Platform MVP | MCT | Power BI Super User | Global Power Platform Hero| Power Platform Solution Architect| Technical reviewer for Packt's books