Power Query syntax is based on a functional language called M (formally known as the Power Query Formula Language). It achieves data transformation by defining a sequence of steps where each step transforms the output of the previous one, eventually resulting in a final table or value. To use it, you need a tool that supports Power Query, such as Microsoft Excel or Power BI Desktop.

What You'll Need

  • Microsoft Excel (with Power Query enabled) or Power BI Desktop.
  • A data source to transform (CSV, Excel workbook, SQL database, or Web API).
  • Access to the Advanced Editor to write and edit M code manually.

Step-by-Step

  1. Open the Power Query Editor: In Excel, go to the Data tab and select Get Data. In Power BI, select Transform Data from the Home ribbon. Once the editor opens, you can use the GUI to create steps, which Power Query automatically translates into M syntax.
  2. Access the Advanced Editor: To see and edit the raw syntax, go to the View tab and click Advanced Editor. This opens a window showing the full M script for your query. Note that labels and menu locations may differ slightly depending on your version of Excel or Power BI.
  3. Understand the Let...In Block: Every M script is structured around a let and in block. The let block is where you define your variables and transformation steps. The in block specifies which of those steps is the final result to be returned to the spreadsheet or report.
  4. Define Your First Step: Start by connecting to a source. A typical first line looks like Source = Excel.Workbook(File.Contents("C:\Data\Sales.xlsx"), null, true),. Each line in the let block must end with a comma, except for the very last step before the in statement.
  5. Chain Transformations: Create subsequent steps by referencing the name of the previous step. For example, if your first step is named Source, your second step might be FilteredRows = Table.SelectRows(Source, each ([Amount] > 100)),. This tells Power Query to take the Source table and apply a filter to it.
  6. Handle Case Sensitivity: When writing syntax, remember that M is strictly case-sensitive. Table.SelectRows is correct; table.selectrows will result in a syntax error. This applies to both function names and variable names.
  7. Manage Step Names with Spaces: If you use the GUI, Power Query often creates step names with spaces, such as "Filtered Rows". To reference these in the syntax, you must wrap them in quotes and precede them with a hashtag: #"Filtered Rows".
  8. Implement Conditional Logic: Use the if...then...else syntax for conditional columns. For example: CustomColumn = Table.AddColumn(PreviousStep, "Category", each if [Sales] > 1000 then "High" else "Low"),.
  9. Close and Apply: Once your syntax is correct, click Done in the Advanced Editor. Then, click Close & Apply (Power BI) or Close & Load (Excel) to bring the transformed data into your workspace.

Common Mistakes

The most frequent error is the missing comma at the end of a step. Because the let block is a list of definitions, every line except the final one must end with a comma. If you add a new step at the bottom of your list, remember to go back and add a comma to the previous line.

Another common mistake is ignoring case sensitivity. Many users coming from SQL or DAX expect functions to be case-insensitive. In M, Text.Upper and text.upper are not the same, and the latter will cause the query to fail immediately.

Users also frequently forget the each keyword when performing row-level operations. The each keyword is shorthand for a function that iterates through every row of a table. Without it, Power Query will not know how to apply the logic to the individual records in the column.

Incorrectly referencing the previous step is a major hurdle. If you rename a step in the GUI but manually edit a later step in the Advanced Editor, the chain is broken. Every step must point to the name of the step immediately preceding it (or any previous step in the sequence) to maintain the data flow.

Tips

Use the Formula Bar for quick edits. You don't always need to open the Advanced Editor. By enabling the Formula Bar (View > Formula Bar), you can edit the syntax of the currently selected step in real-time, which is faster for small adjustments like changing a column name or a filter value.

Leverage the Power Query documentation for function discovery. M has hundreds of functions categorized by type (e.g., Table., List., Text., Date.). When in doubt, search for the prefix of the data type you are working with to find the relevant transformation function.

Comment your code for future maintenance. You can add single-line comments using // or multi-line comments using /* ... */. This is critical when building complex queries with dozens of steps, as it allows you or your colleagues to understand why a specific transformation was applied.

Use parameters to make your syntax dynamic. Instead of hard-coding a file path like "C:\Users\Admin\Data.csv", create a Power Query Parameter. You can then reference that parameter name in your syntax, allowing you to change the data source without editing the M code manually.

Troubleshooting

If your query returns a "Token Literal expected" or "Token Comma expected" error, check your punctuation. Ensure every line in the let block ends with a comma and that the final line before in does not have one. Check for unmatched parentheses or quotes in your function calls.

If you encounter a "Expression.Error: The column 'ColumnName' of the table wasn't found" message, it usually means a previous step renamed or removed that column. Check the step immediately preceding the error to verify the exact spelling and casing of the column headers.

When a query runs slowly or hangs, check for "Data Privacy" settings. Power Query sometimes slows down when combining data from two different sources (e.g., a local CSV and a SQL server) due to privacy levels. You can try setting the privacy levels to "Ignore" in the Query Options to see if performance improves, though this should be done with caution regarding sensitive data.

If the Advanced Editor refuses to save your changes, there is likely a syntax error. Power Query will usually highlight the problematic line with a red squiggly line or provide a generic error message at the bottom of the window. Carefully re-read the line for missing quotes or misspelled function names.

Frequently Asked Questions

Is M the same as DAX?

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

Can I write M code without using the GUI?

Yes. While most users use the GUI to generate the code, you can write the entire script from scratch in the Advanced Editor. This is often more efficient for complex loops or custom functions.

Why is my M code not recognizing my column names?

This is usually due to case sensitivity. If your column is named "Sales" but your code refers to [sales], Power Query will not find the column. Ensure the casing matches exactly.

How do I create a custom function in M?

You can create a function by starting your query with a parameter definition using the (parameter) => syntax. For example, (myValue) => let Result = myValue * 2 in Result creates a simple multiplication function.

Does Power Query syntax support loops?

M does not have traditional for or while loops. Instead, it uses recursive functions or functions like List.Generate and List.Accumulate to perform iterative tasks.

Can I use M to connect to an API?

Yes, you can use the Json.Document(Web.Contents("url")) syntax to connect to a REST API, parse the JSON response, and convert it into a table.