August 14, 2020
Introduction to M language
For Power BI version 2.76.5678.782 (December 2019).
Query editor is a capable data editor in Power BI Desktop. Transformations made in Power Query are written in M language. Understanding M is not necessary, but can be a powerful asset for advanced data manipulation. Let’s look at basics of working with M language.
M query structure
M code can be found by selecting a query and then opening Advanced Editor. Code usually starts with let and ends with in statement.
- let part contain all the steps query makes. Each line contains one step.
- in part contains the name of the last step.
Entire code of a query could be read as “let” step1, step2, step3 be “in” step3.
Variables
Every row starts with step’s name and ends with comma, except for the last row that doesn’t end with a comma. Step names are identical to step names in Applied Steps pane.
If variable name contains space it will appear in M code as #”Ime spremenljivke”. This is how M engine handles spaces and understands it is still a single name.
Comments
As in most languages, we can write comments in M code.
- For one line comments we use //.
- For multiple line comments we use /* in */.
M functions
M has more than 700 functions for data editing. M functions start with capital letters, words are separated by full stop. Arguments are given in brackets.
Example: function Date.Month(date), takes an argument date and returns date month.
Function names are descriptive enough to convey their function. Most commonly used functions are already available through icons in Power Query editor. Documentation and examples for each function can be found on https://docs.microsoft.com/en-us/powerquery-m/power-query-m-function-reference.
Values
When we wish to operate with actual values we have to use appropriate commands. For example, to use the date 6/27/2917, we use #date(2017, 6, 26).
Other value commands are listed in the table below.
Value | Syntax |
Null | null |
Logic | true, false |
Number | 0, 1, -1, 1.5, 3.1e^-20 |
Time | #time(01, 12, 50) |
Date | #date(2012, 1, 20) |
Date-time | #datetime(2012, 1, 20, 01, 12, 50) |
Text | “text” |
List | {1, 2, 3} |
Row | [ A = 1, B = 2 ] |
Table | #table({“A”, “B”},{{ 1, 2 }, { 3, 4 }}) |
Function | (parameter) => parameter +1 |