0% found this document useful (0 votes)
27 views8 pages

Optimizing DAX Queries in Power BI Cheatsheet 1729071928

Optimising dax
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views8 pages

Optimizing DAX Queries in Power BI Cheatsheet 1729071928

Optimising dax
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

# [ Optimizing DAX Queries in Power BI ]

1. Basic Optimization Techniques

● Use variables to store intermediate results: VAR TotalSales =


SUM(Sales[Amount])
● Avoid using CALCULATE unnecessarily: TotalSales = SUM(Sales[Amount]) instead
of CALCULATE(SUM(Sales[Amount]))
● Use SUMMARIZE instead of GROUPBY for better performance: SUMMARIZE(Sales,
Sales[Product], "TotalSales", SUM(Sales[Amount]))
● Avoid using FILTER as a table function: CALCULATE(SUM(Sales[Amount]),
Sales[Category] = "Electronics") instead of CALCULATE(SUM(Sales[Amount]),
FILTER(Sales, Sales[Category] = "Electronics"))
● Use TREATAS for virtual relationships: CALCULATE(SUM(Sales[Amount]),
TREATAS(VALUES(Product[Category]), Sales[ProductCategory]))
● Leverage KEEPFILTERS for preserving existing filters:
CALCULATE(SUM(Sales[Amount]), KEEPFILTERS(Sales[Category] =
"Electronics"))
● Use ALL to remove filters: CALCULATE(SUM(Sales[Amount]), ALL(Sales))
● Utilize ALLEXCEPT to remove specific filters: CALCULATE(SUM(Sales[Amount]),
ALLEXCEPT(Sales, Sales[Date]))
● Implement ALLSELECTED for dynamic base tables: CALCULATE(SUM(Sales[Amount]),
ALLSELECTED(Sales))
● Use SELECTEDVALUE for single selection scenarios:
SELECTEDVALUE(Product[Category], "All Categories")

2. Time Intelligence Optimization

● Optimize YTD calculations: TOTALYTD(SUM(Sales[Amount]), 'Date'[Date])


● Use DATESYTD for custom year-end dates: CALCULATE(SUM(Sales[Amount]),
DATESYTD('Date'[Date], "6-30"))
● Optimize QTD calculations: TOTALQTD(SUM(Sales[Amount]), 'Date'[Date])
● Implement MTD efficiently: TOTALMTD(SUM(Sales[Amount]), 'Date'[Date])
● Use DATESBETWEEN for custom date ranges: CALCULATE(SUM(Sales[Amount]),
DATESBETWEEN('Date'[Date], [StartDate], [EndDate]))
● Optimize previous year comparisons: CALCULATE(SUM(Sales[Amount]),
SAMEPERIODLASTYEAR('Date'[Date]))
● Implement rolling 12 months efficiently: CALCULATE(SUM(Sales[Amount]),
DATESINPERIOD('Date'[Date], MAX('Date'[Date]), -12, MONTH))
● Use PARALLELPERIOD for offset time comparisons: CALCULATE(SUM(Sales[Amount]),
PARALLELPERIOD('Date'[Date], -1, YEAR))
● Optimize fiscal year calculations: CALCULATE(SUM(Sales[Amount]),
DATESYTD('Date'[Date], "9-30"))

By: Waleed Mousa


● Implement custom time intelligence: CALCULATE(SUM(Sales[Amount]),
'Date'[DateKey] <= MAX('Date'[DateKey]) && 'Date'[DateKey] >
MAX('Date'[DateKey]) - 90)

3. Context Transition Optimization

● Avoid unnecessary context transition: SUMX(Sales, Sales[Quantity] *


Sales[Price]) instead of SUM(Sales[Quantity] * Sales[Price])
● Use CALCULATETABLE for efficient context transition:
CALCULATETABLE(VALUES(Product[Category]), Sales[ProductID] =
EARLIER(Product[ProductID]))
● Leverage EARLIER for row context references: AVERAGEX(Product, [Sales Amount]
/ EARLIER([Total Sales]))
● Implement CROSSJOIN for Cartesian products:
GENERATE(VALUES(Product[Category]),
CALCULATETABLE(VALUES(Store[Country])))
● Use ADDCOLUMNS for adding calculated columns efficiently:
ADDCOLUMNS(VALUES(Product[Category]), "Sales",
CALCULATE(SUM(Sales[Amount])))
● Optimize MAXX with context transition: MAXX(SUMMARIZE(Sales,
Sales[ProductID], "TotalSales", SUM(Sales[Amount])), [TotalSales])
● Implement MINX efficiently: MINX(SUMMARIZE(Sales, Sales[ProductID],
"TotalSales", SUM(Sales[Amount])), [TotalSales])
● Use TOPN with context transition: TOPN(5, SUMMARIZE(Sales, Sales[ProductID],
"TotalSales", SUM(Sales[Amount])), [TotalSales], DESC)
● Optimize RANKX calculations: RANKX(ALL(Product), [Sales Amount],, DESC,
Dense)
● Implement efficient running totals: SUMX(FILTER(ALL('Date'), 'Date'[Date] <=
MAX('Date'[Date])), [Sales Amount])

4. Filter Optimization

● Use INTERSECT for efficient filtering: CALCULATE(SUM(Sales[Amount]),


INTERSECT(VALUES(Product[Category]), {"Electronics", "Clothing"}))
● Implement EXCEPT for exclusion filtering: CALCULATE(SUM(Sales[Amount]),
EXCEPT(ALL(Product[Category]), VALUES(Product[Category])))
● Use CROSSFILTER for dynamic relationship filtering:
CALCULATE(SUM(Sales[Amount]), CROSSFILTER(Sales[StoreID], Store[StoreID],
BOTH))
● Optimize USERELATIONSHIP for alternative relationships:
CALCULATE(SUM(Sales[Amount]), USERELATIONSHIP(Sales[CustomerID],
Customer[CustomerID]))

By: Waleed Mousa


● Implement LOOKUPVALUE for efficient single value retrieval:
LOOKUPVALUE(Product[Category], Product[ProductID],
SELECTEDVALUE(Sales[ProductID]))
● Use ISINSCOPE for dynamic level-of-detail calculations:
IF(ISINSCOPE(Product[Category]), SUM(Sales[Amount]), BLANK())
● Optimize ISFILTERED for conditional calculations:
IF(ISFILTERED(Product[Category]), SUM(Sales[Amount]), "All Categories")
● Implement HASONEVALUE for single selection scenarios:
IF(HASONEVALUE(Product[Category]), SELECTEDVALUE(Product[Category]),
"Multiple Categories")
● Use ISEMPTY for checking empty tables: IF(ISEMPTY(FILTER(Sales, Sales[Amount]
< 0)), "No Negative Sales", "Has Negative Sales")
● Optimize CONTAINSROW for efficient row checking:
IF(CONTAINSROW(VALUES(Product[Category]), "Electronics"), "Has
Electronics", "No Electronics")

5. Calculation Optimization

● Use DISTINCTCOUNT instead of COUNTROWS(DISTINCT()):


DISTINCTCOUNT(Sales[CustomerID])
● Implement COUNTAX for non-blank counting: COUNTAX(Sales, Sales[Quantity])
● Use COUNTA for counting non-blank text values: COUNTA(Customer[Email])
● Optimize AVERAGEX calculations: AVERAGEX(Sales, Sales[Quantity] *
Sales[Price])
● Implement MEDIANX for efficient median calculations: MEDIANX(Sales,
Sales[Amount])
● Use STDEVX.P for population standard deviation: STDEVX.P(Sales,
Sales[Amount])
● Optimize VARX.S for sample variance: VARX.S(Sales, Sales[Amount])
● Implement PERCENTILEX.INC for percentile calculations: PERCENTILEX.INC(Sales,
Sales[Amount], 0.9)
● Use GEOMEANX for geometric mean calculations: GEOMEANX(Sales,
Sales[GrowthRate] + 1) - 1
● Optimize PRODUCTX for cumulative multiplication: PRODUCTX(Sales,
Sales[Quantity])

6. Text and Date Manipulation Optimization

● Use CONCATENATEX for efficient string concatenation:


CONCATENATEX(VALUES(Product[Category]), Product[Category], ", ")
● Implement REPLACE for optimized string replacement: REPLACE(Product[Name], 1,
3, "NEW")
● Use LEFT for efficient substring extraction: LEFT(Customer[Name], 5)
● Optimize RIGHT for extracting end of strings: RIGHT(Customer[Phone], 4)

By: Waleed Mousa


● Implement LEN for string length calculations: LEN(TRIM(Customer[Address]))
● Use FORMAT for efficient date formatting: FORMAT('Date'[Date], "MMM YYYY")
● Optimize YEAR, MONTH, DAY functions: YEAR('Date'[Date])
● Implement WEEKDAY for day of week calculations: WEEKDAY('Date'[Date], 2)
● Use WEEKNUM for week number calculations: WEEKNUM('Date'[Date], 21)
● Optimize DATEDIFF for date difference calculations: DATEDIFF('Date'[Date],
[ReferenceDate], DAY)

7. Error Handling and Conditional Logic

● Use IFERROR for error handling: IFERROR(Sales[Revenue] / Sales[Units], 0)


● Implement IF for simple conditional logic: IF(Sales[Amount] > 1000, "High",
"Low")
● Use SWITCH for multiple conditions: SWITCH(TRUE(), Sales[Amount] > 1000,
"High", Sales[Amount] > 500, "Medium", "Low")
● Optimize AND for multiple condition checking: AND(Sales[Amount] > 1000,
Sales[Quantity] > 10)
● Implement OR for alternative condition checking: OR(Sales[Category] =
"Electronics", Sales[Category] = "Computers")
● Use NOT for condition negation: NOT(ISBLANK(Sales[Amount]))
● Optimize ISBLANK for blank value checking: ISBLANK(Customer[Email])
● Implement COALESCE for handling multiple potential blank values:
COALESCE(Sales[ActualAmount], Sales[EstimatedAmount], 0)
● Use DIVIDE for safe division operations: DIVIDE(Sales[Revenue], Sales[Units],
0)
● Implement UNICHAR for dynamic symbol generation: UNICHAR(9733) (returns a star
character)

8. Advanced DAX Patterns

● Implement rolling average: AVERAGEX(DATESINPERIOD('Date'[Date],


MAX('Date'[Date]), -6, MONTH), [Sales Amount])
● Use parameter tables for dynamic measures:
SWITCH(SELECTEDVALUE(Parameter[Value]), "Sum", SUM(Sales[Amount]),
"Average", AVERAGE(Sales[Amount]))
● Implement dynamic Top N calculations: CALCULATE(SUM(Sales[Amount]),
TOPN(SELECTEDVALUE(Parameter[TopN]), VALUES(Product), [Sales Amount],
DESC))
● Use DAX for dynamic grouping: SWITCH(TRUE(), Sales[Amount] < 100, "Low",
Sales[Amount] < 1000, "Medium", "High")
● Implement time-based calculations: CALCULATE([Sales Amount],
DATESINPERIOD('Date'[Date], MAX('Date'[Date]), -1, YEAR))

By: Waleed Mousa


● Use virtual tables for complex calculations:
SUMMARIZECOLUMNS(Customer[CustomerID], "LTV", CALCULATE([Total Sales] +
[Projected Sales]))
● Implement dynamic currency conversion: [Sales Amount] *
LOOKUPVALUE(ExchangeRates[Rate], ExchangeRates[CurrencyCode], [Selected
Currency])
● Use segmentation for customer analysis: SWITCH(TRUE(), [Customer LTV] > 1000,
"High Value", [Customer LTV] > 500, "Medium Value", "Low Value")
● Implement dynamic date ranges: DATESBETWEEN('Date'[Date], [Start Date], [End
Date])
● Use DAX for anomaly detection: IF(ABS(([Sales Amount] - [Average Sales]) /
[Sales StDev]) > 2, "Anomaly", "Normal")

9. Performance Optimization Techniques

● Use variables to cache subexpressions: VAR CachedSales =


CALCULATE(SUM(Sales[Amount])) RETURN CachedSales / [Total Sales]
● Implement SUMMARIZE for pre-aggregation: SUMMARIZE(Sales, Product[Category],
"TotalSales", SUM(Sales[Amount]))
● Use ADDCOLUMNS for efficient column addition:
ADDCOLUMNS(VALUES(Product[Category]), "Sales",
CALCULATE(SUM(Sales[Amount])))
● Optimize CALCULATETABLE for table operations: CALCULATETABLE(VALUES(Product),
Sales[Date] = MAX(Sales[Date]))
● Implement GENERATE for table expansion: GENERATE(VALUES(Product[Category]),
CALCULATETABLE(VALUES(Store[Country])))
● Use CROSSJOIN for efficient Cartesian products:
CROSSJOIN(VALUES(Product[Category]), VALUES(Store[Country]))
● Optimize FILTER for table filtering: FILTER(Sales, Sales[Date] > DATE(2022,
1, 1))
● Implement SELECTCOLUMNS for column selection: SELECTCOLUMNS(Sales, "Date",
Sales[Date], "Amount", Sales[Amount])
● Use GROUPBY for efficient grouping: GROUPBY(Sales, Sales[ProductID],
"TotalSales", SUMX(CURRENTGROUP(), Sales[Amount]))
● Optimize UNION for combining tables: UNION(InternetSales, StoreSales)

10. Query Reduction and Optimization

● Use ALL to remove filters efficiently: CALCULATE([Total Sales], ALL(Product))


● Implement ALLSELECTED for preserving user selections: CALCULATE([Total Sales],
ALLSELECTED(Product))
● Use ALLNOBLANKROW to exclude blank rows: CALCULATE([Total Sales],
ALLNOBLANKROW(Product))
● Optimize FILTERS for retrieving active filters: FILTERS(Product)
By: Waleed Mousa
● Implement ISFILTERED for filter detection: IF(ISFILTERED(Product[Category]),
"Filtered", "Not Filtered")
● Use REMOVEFILTERS for selective filter removal: CALCULATE([Total Sales],
REMOVEFILTERS(Product[Category]))
● Optimize KEEPFILTERS for filter preservation: CALCULATE([Total Sales],
KEEPFILTERS(Product[Category] = "Electronics"))
● Implement ALLEXCEPT for selective filter clearing: CALCULATE([Total Sales],
ALLEXCEPT(Product, Product[Category]))
● Use SELECTEDVALUE for efficient single selection handling:
SELECTEDVALUE(Product[Category], "All Categories")
● Optimize HASONEVALUE for single selection detection:
IF(HASONEVALUE(Product[Category]), "Single Category", "Multiple
Categories")

11. Date and Time Optimization

● Use CALENDAR for generating date tables: CALENDAR(DATE(2020, 1, 1),


DATE(2025, 12, 31))
● Implement CALENDARAUTO for dynamic date ranges: CALENDARAUTO(6)
● Use DATESYTD for year-to-date calculations: CALCULATE([Total Sales],
DATESYTD('Date'[Date]))
● Optimize DATESQTD for quarter-to-date calculations: CALCULATE([Total Sales],
DATESQTD('Date'[Date]))
● Implement DATESMTD for month-to-date calculations: CALCULATE([Total Sales],
DATESMTD('Date'[Date]))
● Use DATEADD for date shifting: CALCULATE([Total Sales],
DATEADD('Date'[Date], -1, YEAR))
● Optimize DATESINPERIOD for custom periods: CALCULATE([Total Sales],
DATESINPERIOD('Date'[Date], LASTDATE('Date'[Date]), -6, MONTH))
● Implement FIRSTDATE for period start dates: FIRSTDATE('Date'[Date])
● Use LASTDATE for period end dates: LASTDATE('Date'[Date])
● Optimize STARTOFYEAR for fiscal year calculations: STARTOFYEAR('Date'[Date])

12. Statistical and Mathematical Optimization

● Use RANKX for efficient ranking: RANKX(ALL(Product), [Sales Amount],, DESC,


Dense)
● Optimize PERCENTILE.EXC for exclusive percentile calculations:
PERCENTILE.EXC(Sales[Amount], 0.95)
● Use GEOMEAN for geometric mean calculations: GEOMEAN(Sales[GrowthRate])
● Implement MEDIAN for efficient median calculations: MEDIAN(Sales[Amount])
● Optimize STDEV.P for population standard deviation: STDEV.P(Sales[Amount])
● Use VAR.S for sample variance calculations: VAR.S(Sales[Amount])
● Implement BETA.DIST for beta distribution: BETA.DIST(0.4, 2, 3, TRUE)
By: Waleed Mousa
● Optimize CHISQ.DIST for chi-square distribution: CHISQ.DIST(0.5, 1, TRUE)
● Use CONFIDENCE.NORM for confidence interval calculations:
CONFIDENCE.NORM(0.05, STDEV.P(Sales[Amount]), COUNTROWS(Sales))
● Implement CORREL for correlation coefficient: CORREL(Sales[Price],
Sales[Quantity])

13. Text and String Manipulation Optimization

● Use CONCATENATEX for efficient string concatenation:


CONCATENATEX(VALUES(Product[Category]), Product[Category], ", ")
● Optimize FIND for substring position: FIND("a", Product[Name], 1, -1)
● Implement REPLACE for string replacement: REPLACE(Product[Name], 1, 3, "NEW")
● Use REPT for string repetition: REPT("*", 5)
● Optimize SEARCH for case-insensitive substring search: SEARCH("product",
Product[Description], 1, -1)
● Implement SUBSTITUTE for multiple replacements: SUBSTITUTE(Product[Name], "
", "_", 0)
● Use TRIM for removing leading and trailing spaces: TRIM(Customer[Name])
● Optimize UNICHAR for Unicode character generation: UNICHAR(9733) (returns a
star character)
● Implement UPPER for uppercase conversion: UPPER(Product[Category])
● Use LOWER for lowercase conversion: LOWER(Customer[Email])

14. Advanced Filtering and Slicing

● Use TREATAS for virtual relationships: CALCULATE([Total Sales],


TREATAS(VALUES(Product[Category]), Sales[ProductCategory]))
● Implement INTERSECT for efficient multi-selection filtering: CALCULATE([Total
Sales], INTERSECT(VALUES(Product[Category]), {"Electronics",
"Clothing"}))
● Optimize EXCEPT for exclusion filtering: CALCULATE([Total Sales],
EXCEPT(ALL(Product[Category]), VALUES(Product[Category])))
● Use SELECTEDVALUE for default values in slicers:
SELECTEDVALUE(Product[Category], "All Categories")
● Implement ISSELECTEDMEASURE for dynamic measure selection:
IF(ISSELECTEDMEASURE([Total Sales]), [Total Sales], [Total Cost])
● Optimize CROSSFILTER for dynamic relationship filtering: CALCULATE([Total
Sales], CROSSFILTER(Sales[ProductID], Product[ProductID], BOTH))
● Use USERELATIONSHIP for alternate relationship paths: CALCULATE([Total Sales],
USERELATIONSHIP(Sales[CustomerID], Customer[CustomerID]))
● Implement SUMMARIZECOLUMNS for efficient summarization with filters:
SUMMARIZECOLUMNS(Product[Category], TREATAS({"Electronics", "Clothing"},
Product[Category]), "TotalSales", [Total Sales])

By: Waleed Mousa


● Optimize ALLSELECTED for preserving user selections: CALCULATE([Total Sales],
ALLSELECTED(Product))
● Use MATCHES for pattern matching in filters: CALCULATE([Total Sales],
FILTER(Product, MATCH(Product[SKU], "A*") > 0))

15. Optimization for Large Datasets

● Implement columnstore indexes for better compression: CREATE CLUSTERED


COLUMNSTORE INDEX ON FactSales
● Use partitioning for large fact tables: CREATE PARTITION FUNCTION
[PF_Date](DATE) AS RANGE RIGHT FOR VALUES ('2022-01-01', '2023-01-01',
'2024-01-01')
● Implement aggregations for faster query performance: CREATE AGGREGATION ON
Sales BASED ON FactSales (Date TO Date.Month, Product TO
Product.Category, SUM(Amount))
● Optimize with DirectQuery storage mode: Set table storage mode to DirectQuery
for real-time data
● Use composite models for mixing Import and DirectQuery: Set large fact tables
to DirectQuery and dimension tables to Import mode
● Implement incremental refresh: Configure incremental refresh policy on large
fact tables
● Use Power Query (M) for complex data transformations: Transform data in Power
Query to reduce DAX complexity
● Optimize dataflows for reusable ETL processes: Create and use dataflows for
common data preparation steps
● Implement query folding for improved performance: Ensure Power Query steps are
foldable to push computation to the source
● Use AsType for early data type enforcement:
Table.TransformColumnTypes(Source, {{"ID", Int64.Type}, {"Name", type
text}})

16. Model Design Optimization

● Implement star schema for optimal performance: Design fact and dimension
tables in a star schema pattern
● Use surrogate keys for dimension tables: Add an identity column as a
surrogate key in dimension tables
● Implement slowly changing dimensions (SCD) Type 2: Add ValidFrom and ValidTo
columns to track historical changes
● Optimize many-to-many relationships: Use a bridge table to resolve
many-to-many relationships
● Implement role-playing dimensions: Create multiple relationships between
fact and a single dimension table for different roles

By: Waleed Mousa

You might also like