Power Query M functions are custom, reusable formulas you write in the M language that take inputs and return a value or table, letting you replace a pile of repeated transformation steps with a single call. You write them as a let expression returning a function value, then invoke that function on each table, column or query you want to process. This guide walks through creating one, using it, and debugging it when it misbehaves.
What You'll Need
- Excel (any recent desktop version with Power Query, i.e. Data > Get Data), Power BI Desktop, or the Power Query editor in Fabric or Analysis Services.
- A data source already loaded, or an existing query you want to refactor.
- Comfort reading basic M expressions (each transformation step is an M expression, so you have already been writing M without noticing).
- For anything beyond small inline tests, the ability to open the Advanced Editor (Home > Advanced Editor in Excel and Power BI Desktop; labels can differ slightly by version, device or region).
Step-by-Step
- Start with the plain query you already have. Load your data, apply transforms as usual via the ribbon or by hand-editing steps. Confirm the query returns the result you want before generalising it into a function. A function built on a broken transformation helps nobody.
- Identify the parameter(s). Decide what varies between invocations: a table, a column name, a filter value, a date. Anything fixed stays hard-coded inside the function. Start with one parameter; add more only when needed.
- Convert the query into a function template. Right-click the query in the Queries pane and choose Create Function (available in Power Query for Excel and Power BI Desktop). The dialog asks for the function name and lets you mark which parameters should be extracted from existing steps. Alternatively, wrap the query manually.
- Inspect the generated M. Open the Advanced Editor. The generated code is typically of the form
(myTable as table) => let Source = ..., Result = ... in Result(or with aletoutside returning the lambda). The(myTable as table) =>part is the function definition; everything after the arrow runs on each call. - Replace hard-coded values with parameter references. Anywhere the old query had a literal table, column name, filter value or date, use the corresponding parameter name. Keep
as table,as text,as numbertype annotations; they improve error messages and let M know what to expect. - Test the function inline before you save. Create a blank query (Home > New Source > Blank Query) and type something like
MyFunction(#"MyQuery")in the formula bar, or build a test table with several rows and call it from the Advanced Editor. If it returns the expected table, the function works. - Use it across your queries. In any query where you want the transformation, go to Home > Advanced Editor and add a step calling the function on your source table. Because the function is stored in the Queries pane as a separate item, it appears in the list of available functions when you type its name.
- Apply it inside a column or table transformation. For example, a function taking a text value and returning a cleaned string can be added as a new column with Table.AddColumn or applied via Table.TransformColumns (choose with a call such as — the is the important part, because it passes each row's value into the function).
- Give it a good name and, if relevant, a description. Use a name without spaces or punctuation where possible (e.g.
fnCleanName). The description field appears when the function is used elsewhere and helps anyone else working in the workbook. - Remove the scaffolding. Once the function works, delete any test queries you made to validate it, and confirm every query that consumes the function still loads and refreshes cleanly. Use Home > Refresh All to run through the whole model.
- Keep it isolated. Store shared helper functions in a dedicated group (right-click the Queries pane > New Group), and never disable their load or delete them if other queries reference them. Deleting a referenced function breaks every query that uses it.
Common Mistakes
- Forgetting the arrow. A function is a value of the form
(x as table) => expression. A query with the same code but no=>is just a table; calling it with parentheses produces an error. - Passing a query name as text.
MyFunction("Sales")passes the text "Sales", not the Sales query. Use the query name without quotes so M resolves it, or use#"Sales"to escape a name with spaces. - Case sensitivity. M is case-sensitive, and identifiers with spaces or other characters must be escaped with
#"...".MyTable,mytableandMyTableas a bare identifier are not the same. - Triggering the function's own evaluation repeatedly. Each call re-evaluates the table input. Passing a full query into a function called from another query is fine; calling a slow function thousands of times in a column will be slow. Consider bulk Table.TransformColumns techniques instead.
- Forgetting a type annotation. Omitting it works, but M will accept text where you expected a table, and errors surface later at a confusing step.
- Hard-coding a source step inside the function. If the function opens its own CSV or database connection, every call re-reads the file. Pass the table in as a parameter instead.
Tips
- Right-click any existing step and copy its M code into a scratch query to see the exact syntax — a fast way to learn idioms without guessing.
- Use
try ... otherwiseto degrade gracefully:try f([Col]) otherwise nullreturns null on error rather than aborting the whole query. - Name functions with a prefix (e.g.
fn) so they are easy to spot in the Queries pane. - When a function starts taking many parameters, check whether a record parameter is cleaner:
fnClean(record[Table, Column, Value]). - Use
eachand_only inside function contexts where the row context is defined (e.g.Table.TransformColumns,Table.SelectRows,Table.AddColumn). At top level_is not defined.
Troubleshooting
The function shows as a table, not a function. The => is missing, or you are viewing the result rather than the definition. Open the Advanced Editor and confirm the arrow after the parameter list.
"We cannot convert a value of type Text to type Table" (or similar). A parameter is receiving the wrong type. Pass the query itself (not its name in quotes) and check that the parameter's as table annotation matches what you are giving it.
"The field 'X' of the record wasn't found." A column lookup is wrong. Confirm the exact column name (case and spaces matter) and consider Record.FieldOrDefault or Table.ColumnNames to inspect names at runtime.
Query steps disappeared or a referenced query is missing. Deleting the function query breaks all consumers. Restore it from a backup of the workbook or recreate it; every consumer then needs re-pointing.
The refresh is very slow after adding the function. The function is re-running its source on every call, or calling a costly transform per row. Pass the table as a parameter and let the function do only the transformation.
Errors return nothing useful. Wrap the step in try ... otherwise while debugging, and split the function into smaller guarded steps. Check the error message's details, not only the summary line.
If that did not work, break the function down: copy each internal step into a test query, call the function on a one-row table, and add steps back one by one. If a single step still fails, fix that step in a plain query first, then move the code back into the function.
Frequently Asked Questions
What is the difference between a Power Query function and a query?
A query returns a value (usually a table). A function returns a value that depends on parameters and produces a result only when called. They live in the same Queries pane, so it helps to name them differently.
Do I need to know M to create functions?
Not to create one, since Create Function generates the wrapper for you. You will need at least to read M to edit parameters and replace hard-coded values reliably.
Can a function call another function?
Yes. Functions are values in the workbook's M environment, so one function can call another by name, and chaining small functions is usually easier to test than one large one.
Does a custom function work in Excel and Power BI alike?
Yes, the M language is the same. Custom functions must be created inside the same query environment where they are used; a function created in one workbook does not automatically exist in another.
Why does my function fail when called from a different query?
Most often because the second query passes a different table shape, uses a column name with different case or spacing, or the function's parameter type does not match what is passed. Check the input first, not the function body.
Should I put functions in the data model or keep them as queries?
Keep them as queries and set them not to load (right-click > untick Enable Load) where available, since they hold code, not data. Loading a function as a table produces an empty or nonsensical result and confuses downstream users.