Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query Formulas: How to Use M Language Effectively

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Power Query formulas allow you to transform, clean, and reshape data by using the M formula language to perform actions that go beyond the standard ribbon buttons. To use them, you primarily use the Formula Bar or the Advanced Editor within the Power Query Editor in Excel or Power BI. This achieves a higher level of automation and precision, enabling you to create complex conditional columns, perform advanced date calculations, and merge disparate data sources with custom logic.

What You'll Need

  • Microsoft Excel (with Power Query installed) or Power BI Desktop.
  • A dataset imported into the Power Query Editor.
  • The Formula Bar enabled (found under the View tab in the Power Query Editor).

Step-by-Step

  1. Enable the Formula Bar: Open the Power Query Editor. Go to the View tab on the top ribbon and check the box for Formula Bar. This allows you to see and edit the M code for every step you apply to your data. Note that menu labels may differ slightly depending on your version of Excel or Power BI.
  2. Create a Custom Column: Navigate to the Add Column tab and select Custom Column. A dialog box will appear where you can enter your formula. This is the safest way to start writing M code because the interface provides a list of available function categories and a helper box to show if your syntax is correct.
  3. Writing a Basic Conditional Formula: In the Custom Column dialog, use the if...then...else structure. For example, if you want to categorize sales, write: if [Sales] > 1000 then "High" else "Low". Ensure you use double quotes for text strings and square brackets for column names.
  4. Using Built-in M Functions: To perform more complex tasks, use the Text, Number, or Date libraries. For instance, to extract the first three characters of a product code, use Text.Start([ProductCode], 3). To find the start of the month for a date column, use Date.StartOfMonth([OrderDate]).
  5. Editing Existing Steps: Look at the Applied Steps pane on the right. Click on a step, then look at the Formula Bar. You can manually change the parameters. For example, if a "Filtered Rows" step says = Table.SelectRows(#"Previous Step", each ([Status] = "Active")), you can change "Active" to "Pending" directly in the bar to update the filter.
  6. Accessing the Advanced Editor: For multi-step logic or creating custom functions, go to the Home tab and click Advanced Editor. This opens the full script of the query. The script always starts with a let block (where variables and steps are defined) and ends with an in block (which specifies the final result to be displayed).
  7. Defining a Custom Function: In the Advanced Editor, you can create a reusable formula by starting with a parameter. For example: (Price) => let Tax = Price * 0.15 in Price + Tax. Save this as a query, and you can then invoke it on any column in other tables using the Invoke Custom Function tool.
  8. Closing and Applying: Once your formulas are working, go to the Home tab and select Close & Apply. This pushes the transformed data back into the Excel worksheet or the Power BI data model.

Common Mistakes

The most frequent error in Power Query formulas is ignoring case sensitivity. M is a case-sensitive language. Writing table.selectrows instead of Table.SelectRows will result in a syntax error. Similarly, if your data contains "Active" but your formula looks for "active", it will not find a match.

Another common mistake is forgetting the else statement in a conditional formula. Unlike some programming languages where an else is optional, Power Query requires a complete if...then...else chain. If you do not have a specific alternative, you must use else null.

Users also frequently confuse the square bracket notation. Square brackets [ColumnName] are used exclusively for referencing columns in the current row context. If you attempt to use them to reference a previous step or a separate table, the formula will fail.

Finally, many beginners forget to handle null values. If a formula performs a mathematical operation on a cell containing a null, the entire result for that row becomes null. You must use if [Column] = null then 0 else [Column] to ensure calculations proceed correctly.

Tips

To speed up your workflow, use the "Insert Step" button (the fx icon next to the formula bar). This allows you to create a new step based on the previous one without needing to use the Add Column menu, which is ideal for renaming tables or performing bulk transformations.

When dealing with long formulas in the Advanced Editor, use indentation. While M doesn't require it for execution, indenting the code inside the let block makes it significantly easier to debug and maintain. Use a comma at the end of every line except for the final line before the in statement.

Leverage the Value.NativeQuery function when working with SQL databases. This allows you to write the formula in the database's native language (SQL), which is often faster because the server does the heavy lifting before the data even reaches Power Query (a process known as Query Folding).

Use the try...otherwise pattern for error handling. Instead of letting a query fail because of a single bad data point, you can wrap your formula: try [Amount] / [Quantity] otherwise 0. This ensures your data refresh completes even if some rows contain zeros or text in numeric columns.

Troubleshooting

If your formula returns a "Token Literal expected" error, check your quotes. Ensure you are using standard straight quotes (" ") and not curly "smart quotes" often produced by word processors. Also, verify that every open parenthesis ( has a corresponding closing parenthesis ).

If you see a "The column 'X' of the table wasn't found" error, check the step immediately preceding the current one. Power Query references the name of the previous step. If you renamed a column in Step 2, but Step 3 is still trying to find the old name, the query will break. Update the column name in the formula bar to match the current state of the table.

When a formula is running extremely slowly, check for "Step Explosion." This happens when you create too many individual steps that force Power Query to reload the entire dataset multiple times. Try combining multiple transformations into a single custom column or using the Advanced Editor to merge similar steps.

If the data type is not what you expected after a formula (e.g., a number is showing as text), manually add a "Change Type" step immediately after your custom formula. Power Query often assigns the "Any" type to custom columns, which can cause issues in downstream reports.

Frequently Asked Questions

Is M the same as DAX?

No. M is a data transformation language used in the Power Query Editor to clean and shape data before it enters the model. DAX (Data Analysis Expressions) is a formula language used for creating measures and calculated columns within the data model for analysis.

Can I use Power Query formulas in standard Excel cells?

No. Power Query formulas are written in M and only function within the Power Query Editor environment. To get the results into Excel cells, you must load the query as a Table or a Connection.

How do I find a list of all available M functions?

While there is no built-in searchable library inside the editor, the official Microsoft documentation for the Power Query M formula language provides a comprehensive list of functions categorized by type (Text, Date, List, Table, etc.).

Why does my formula work for some rows but return an error for others?

This is usually due to data type mismatches or null values. For example, trying to use Text.Upper on a cell that contains a number will trigger an error. Use the try...otherwise block to handle these exceptions.

Can I reference a value from a different cell in the same row?

Yes. You do this by referencing the column names in square brackets. For example, [UnitPrice] * [Quantity] will multiply the values of those two columns for every row in the table.

Do I need to be a programmer to use M formulas?

No. Most users can achieve their goals using the ribbon buttons. Formulas are only necessary for complex logic that the standard interface cannot handle, and they can be learned incrementally by observing the formula bar.