DAX user-defined functions: write the logic once

A DAX user-defined function packages DAX logic with parameters, so measures, calculated columns, visual calculations and other functions call it instead of repeating it. Define it with the FUNCTION keyword in DAX query view or TMDL view. It is generally available since the June 2026 Power BI release and needs compatibility level 1702 or higher.

Get the project

Analysts · ·

The problem

The same DAX sits in a dozen measures: a safe divide, a percentage, a year-over-year change. Someone fixes one copy and the others stay as they were. You build and maintain semantic models in Power BI and you want one definition that every measure calls. This Pattern shows how to define a DAX user-defined function, which parameter types to use, and where the limits are.

What is generally available and what is not

Status is stated per feature, with its source.

Part Status Where it comes from
DAX user-defined functions in Power BI Desktop and the Power BI service Generally available since the June 2026 update (2.155.756.0) Monthly update archive, row “DAX user-defined functions (Generally Available)”; the DAX UDF page and the overview page say the same
Optional parameters (default expressions) Listed in the same June 2026 update, without a preview mark Monthly update archive, row “DAX UDF optional parameters”
View and edit UDFs in the browser Stated on the overview page, under web modeling Overview page
TMDL view in web modeling Listed as preview in the March 2026 update; current status not checked Monthly update archive, March 2026

The feature was in preview in 2025 and the first half of 2026, so guides from that time describe a preview. The documentation read on 2026-11-29 states general availability. No Microsoft source read says otherwise. The June 2026 feature summary that the archive links to was not read.

Steps

Two columns: three measures that repeat the same logic, and one function that the same three measures call.

The same logic copied three times, and written once as a function.

You can try the examples in DAX query view with your own model.

  1. Find the logic you copy. Look for the same expression in several measures, for example a division that must not fail on zero. That is the function.

  2. Define it in DAX query view and test it. Written for this article.

    DEFINE
        /// Divides num by den and returns BLANK when den is zero
        FUNCTION Util.SafeDivide = ( num : NUMERIC, den : NUMERIC ) =>
            DIVIDE ( num, den )
    
        /// Relative change between a current and a previous value
        FUNCTION Util.PctChange = ( current : NUMERIC, previous : NUMERIC ) =>
            Util.SafeDivide ( current - previous, previous )
    
    EVALUATE
    { Util.SafeDivide ( 5, 2 ), Util.SafeDivide ( 5, 0 ), Util.PctChange ( 110, 100 ) }
    

    By the definition of DIVIDE, the three values should be 2.5, BLANK and 0.1. Dots in a function name give a namespace; they cannot start, end or repeat in a name. One function calling another is allowed.

    The same tool, with Microsoft’s own example. From the DAX UDF page:

    DEFINE
        /// AddTax takes in amount and returns amount including tax
        /// @param {NUMERIC} amount - The pre-tax value to which tax will be applied
        /// @param {NUMERIC} [taxRate] - Optional tax rate to apply, default is 0.1 (10%)
        /// @returns The amount including 10% tax
        FUNCTION AddTax =
            ( amount : NUMERIC, taxRate : NUMERIC = 0.1 ) =>
                amount * ( 1 + taxRate )
    
    EVALUATE
    { AddTax ( 10 ) }
    // Returns 11
    

    Use /// for descriptions. Single-line // and /* */ comments do not appear in IntelliSense. taxRate = 0.1 makes the parameter optional.

  3. Save it to the model. In DAX query view, click “Update model with changes” to save every function in the query, or “Update model: Add new function” above one function. In TMDL view the form is different and you click Apply. From the DAX UDF page:

    createOrReplace
        /// AddTax takes in amount and returns amount including tax
        function AddTax = (amount : NUMERIC) => amount * 1.1
    
  4. Call it. A UDF works like a built-in function, in a measure, a calculated column, a visual calculation or another UDF. From the DAX UDF page:

    Total Sales with Tax = AddTax ( [Total Sales] )
    Sales Amount with Tax = CONVERT ( AddTax ( 'Sales'[Sales Amount] ), CURRENCY )
    

    The first line is a measure, the second a calculated column. In a calculated column the function must return a scalar of one consistent type; convert the result if needed. In a visual calculation you cannot pass model objects that are not in the visual.

  5. Choose the parameter types. A parameter has up to three hints, in this order: type, subtype, mode. Without hints it is AnyVal and val. Types are AnyVal, Scalar, Table, and the reference types AnyRef, CalendarRef, ColumnRef, MeasureRef, TableRef. Subtypes include Int64, Decimal, Double, String, DateTime, Boolean and Numeric. Modes are val (evaluated once, before the function runs) and expr (evaluated inside, possibly many times). Reference types must be expr.

    A subtype also casts. From the DAX UDF page:

    DEFINE
        /// returns x as an Int64
        FUNCTION CastToInt = ( x : INT64 ) => x
    
    EVALUATE
    { CastToInt ( 3.4 ), CastToInt ( 3.5 ), CastToInt ( "5" ) }
    // returns 3, 4, 5
    

    The mode decides what the function can do with filters. From the DAX UDF page:

    DEFINE
        /// Table val: receives a materialized table, context can't be changed
        FUNCTION CountRowsNow = ( t : TABLE VAL ) =>
            COUNTROWS ( CALCULATETABLE ( t, ALL ( 'Date' ) ) )
    
        /// Table expr: receives an unevaluated expression, context CAN be changed
        FUNCTION CountRowsLater = ( t : TABLE EXPR ) =>
            COUNTROWS ( CALCULATETABLE ( t, ALL ( 'Date' ) ) )
    
    EVALUATE
    {
        CALCULATE ( CountRowsNow ( 'Sales' ), 'Date'[Fiscal Year] = "FY2020" ),
        CALCULATE ( CountRowsLater ( 'Sales' ), 'Date'[Fiscal Year] = "FY2020" )
    }
    // the two counts differ
    

    The two counts differ. With val, Sales is already filtered to FY2020 when it enters the function, so ALL ( 'Date' ) changes nothing. With expr, the function removes the year filter itself.

  6. Keep the functions in the project. In a Power BI project, the functions are in functions.tmdl inside the definition folder, so they go through Git like the rest of the model.

  7. List what the model has. From the DAX UDF page:

    EVALUATE INFO.USERDEFINEDFUNCTIONS()
    EVALUATE INFO.FUNCTIONS("ORIGIN", "2")
    

    The first returns full metadata and needs write permission. The second returns the names and limited metadata.

  8. Lint the text before you apply it. The project below checks the rules that the documentation states for names, type hints, defaults, recursion and comments. It runs on the text of a .dax or .tmdl file.

The project

Get the project

dax-udf-lint is a small Python project that needs no Power BI and no Fabric tenant. It reads UDF definitions in query-view form or TMDL form and reports rule violations: name and parameter-name characters, three reserved words, duplicate names, more than 256 parameters, invalid type-hint combinations, direct and mutual recursion, defaults that refer to another optional parameter, and missing /// descriptions.

python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python dax_udf_lint.py samples/good.dax samples/functions.tmdl samples/bad.dax && python -m pytest -v

Terminal output of the lint: no errors for the two good files, eleven errors and two warnings for bad.dax, twelve tests passed.

Recorded run of the lint project on 2026-11-29 (one message shortened).

The recorded run (full output in RUN_LOG.txt inside the project) found no errors in good.dax and functions.tmdl, 11 errors and 2 warnings in bad.dax, and 12 tests passed. It proves that the linter applies its rules to the samples. It does not prove that your DAX is correct, or that Power BI accepts a file the linter passes.

Copy this prompt

When several DAX measures repeat a calculation, paste the measures and this prompt into your assistant’s chat. Name the table or visual you will use for comparison. Ask for a reusable function, updated measures and a query that shows the old and new values side by side.

Here are measures that repeat the same logic:
<paste the measures>
Extract one DAX user-defined function with typed parameters. Use NUMERIC or
INT64 subtypes where they fit, and declare reference parameters as ANYREF or
COLUMNREF. Write it in TMDL form (createOrReplace function) with /// lines
above it. Rewrite the measures to call it. Give an EVALUATE query that shows
the old measure and the new measure side by side for every row of
<table or visual>. Do not use recursion, a return type or overloading.

Check the answer for a function that calls itself, hints in an order other than type, subtype, mode, and a missing comparison query. Then run the query in DAX query view and compare the two columns.

Test result

The local checker flagged naming and parameter issues in DAX and TMDL. To compare measure values, run the exercise’s DAX query in your model.

Limits

  • Not supported: recursion and mutual recursion, overloading, an explicit return type, parameter descriptions, display folders, translations, hiding a UDF, models without tables, and returning an enum value.
  • A UDF can have 0 to 256 parameters.
  • Object-level security does not transfer to functions. A function that refers to a secured measure is not secured. Do not put secured names in function names or descriptions.
  • In a live-connected model the functions do not appear in Model explorer. A model-based measure in a composite model cannot refer to UDFs of the source model.
  • A visual calculation can call a UDF, but cannot pass it model objects that are not in the visual.
  • Unqualified names are read as measure references, so formula fix-up and dependency tracking are not reliable for columns written without a table name.
  • IntelliSense is missing in the visual calculation formula bar and in SQL Server Management Studio, and limited in the TMDL extension for Visual Studio Code. Red underlines can appear when you pass columns as expr parameters.
  • Names that clash with built-in DAX functions or reserved words are not allowed. The documentation names measure, function and define; the linter checks only those three.
  • The linter reads text. It cannot tell whether a body is valid DAX.

Sources

Author

Rodrigo Lombana Reina, data engineer. Personal opinions. Checked against the documentation on 2026-11-29.

Questions

What is a DAX user-defined function?

A DAX user-defined function (UDF) is a named piece of DAX logic with parameters that you define once in the model and call like a built-in function. You can use it in a measure, a calculated column, a visual calculation or another UDF. It is defined with the FUNCTION keyword and needs database compatibility level 1702 or higher.

How do I create a user-defined function in Power BI?

Open DAX query view in Power BI Desktop, write DEFINE FUNCTION name = ( parameters ) => expression, test it with EVALUATE, then click Update model with changes to save it. In TMDL view the form is createOrReplace function, saved with Apply. The functions are stored in functions.tmdl in a Power BI project. The steps section shows both forms.

Are DAX user-defined functions generally available or still in preview?

They are generally available in Power BI Desktop and the Power BI service since the June 2026 update, version 2.155.756.0, according to Microsoft Learn's monthly update page and its documentation. They were in preview in 2025 and early 2026. Some related features have a different status: the status section lists what was and was not checked.

Can I use a DAX UDF in the Power BI service?

Yes, to a point. Microsoft's overview says DAX UDFs are generally available in the Power BI service and that you can view and edit them in the browser through web modeling. Authoring in Power BI Desktop (DAX query view, TMDL view, Model view) is the path the documentation describes in detail, so use it for larger changes.

How do I list all user-defined functions in a model?

Run EVALUATE INFO.USERDEFINEDFUNCTIONS() in DAX query view for full metadata, which needs write permission on the model. For names and limited metadata only, run EVALUATE INFO.FUNCTIONS("ORIGIN", "2"). In Power BI Desktop the functions also appear under the Functions node in Model explorer.

Why does my DAX UDF ignore the filter I remove inside it?

Because a table parameter is evaluated before the function runs by default (val). Declare it TABLE EXPR so the function receives an unevaluated expression and can change filter context inside, for example with CALCULATETABLE and ALL. In Microsoft's example the two versions return different row counts.

What are the limits of DAX user-defined functions?

Per Microsoft Learn: no recursion or mutual recursion, no overloading, no explicit return type, no parameter descriptions, no display folders, no translations, and a UDF cannot be hidden. Object-level security does not carry over to functions. Parameters are limited to 256. A UDF cannot return an enum value. The limits section lists the rest.

Should I use a UDF or copy the measure logic?

Use a UDF when the same logic sits in several measures or columns, because a fix is then made once, in one definition. Copying is fine for logic used one time. A UDF comes with limits: it cannot be recursive, hidden or put in a display folder. Microsoft Learn describes UDFs as a way to centralize business rules.

Portrait of Rodrigo Lombana Reina

Rodrigo Lombana Reina, data engineer. Data problems solved, step by step.

About Rodrigo · The opinions and texts on this site are my own.

My LinkedIn profile