Power Query course · Lesson 13 of 17

The M language: let, steps, lists, records, tables and each

Read and write Power Query M: let/in, step names, values, lists, records and tables, item and field access, functions, each and the underscore.

Advanced 22 min read

Every button in the Power Query Editor writes M code. You can build a great deal without reading it, but sooner or later you will need something the buttons cannot do: a filter that depends on another query, a column that looks at the previous row, a step that survives a renamed column. At that point a basic reading knowledge of M turns a dead end into a two-line fix. This lesson is a practical tour of the language, using the code Power Query already writes for you as the starting point.

A query is one let expression

Open any query and choose Home › Advanced Editor. You see a block like this:

Power Query M
let
    Source = Excel.CurrentWorkbook(){[Name="Payroll"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source, {{"Employee", type text}, {"Gross", type number}, {"Dept", type text}}),
    #"Filtered Rows" = Table.SelectRows(#"Changed Type", each [Gross] > 0),
    #"Added Tax" = Table.AddColumn(#"Filtered Rows", "Tax", each [Gross] * 0.22, type number)
in
    #"Added Tax"
let introduces named values (the steps); in says which value the query returns.
  • Between let and in is a comma-separated list of name = expression pairs. Each pair is one step in Applied Steps; the name is the step name.
  • Names with spaces or special characters are written #"Changed Type". A simple name like Source needs no quotes. Renaming a step to Typed makes the code easier to read.
  • Each step usually refers to the previous one, but it may refer to any earlier step, or even to another query by its name.
  • The expression after in is the result. It is normally the last step, but if you write in Source, the query returns the Source step and ignores the rest.
  • There is no comma after the last step before in. A missing or extra comma is the most common syntax error.
  • Comments: // to the end of the line or /* block */.
Tip. M is evaluated lazily: a step that is not needed by the result is not computed. That is why you can leave an experimental step in the middle of a query without slowing it down, as long as nothing refers to it.

Values

KindLiteral exampleNotes
Number42, 3.75, -1e3Decimal point is always a dot in code
Text"Athens"Double quotes; a quote inside is written twice: """Hi"""
Logicaltrue, falseLowercase
NullnullMissing value
Date#date(2026, 3, 15)Also #time, #datetime, #datetimezone
Duration#duration(1, 0, 0, 0)Days, hours, minutes, seconds
List{1, 2, 3}Ordered values in curly braces
Record[Name = "Ana", Age = 31]Named fields in square brackets
Table#table({"A", "B"}, {{1, 2}})Columns and rows
Function(x) => x * 2Functions are values too

Operators: + - * / for numbers, & to join text (and to combine lists or records), = <> for equality, < <= > >=, and the words and, or, not. Remember from Custom and conditional columns: there is no automatic conversion, so "Year " & 2026 is an error; write "Year " & Text.From(2026).

Lists

A list is an ordered sequence in curly braces. Ranges are allowed: {1..12} is the numbers 1 to 12, {"A".."E"} the letters A to E. Item access uses curly braces with a zero-based position: {10, 20, 30}{0} is 10. If the position may not exist, add a question mark: {10, 20}{5}? returns null instead of an error.

Power Query M
let
    Amounts = {1200, 450, 980, 2300},
    Total = List.Sum(Amounts),                      // 4930
    Biggest = List.Max(Amounts),                    // 2300
    Large = List.Select(Amounts, each _ >= 1000),   // {1200, 2300}
    WithVat = List.Transform(Amounts, each _ * 1.24),
    Months = List.Transform({1..12}, each Date.MonthName(#date(2026, _, 1), "en-US"))
in
    Months
List functions: Sum, Max, Select (filter) and Transform (map). Months returns January to December.

Records

A record is a set of named fields, like one row of a table. Access a field with square brackets: [Name = "Ana", Dept = "HR"][Dept] is "HR". With a question mark, rec[Bonus]? gives null when the field does not exist. Inside a table formula, [Gross] is exactly this: a field access on the current row's record.

Tables, columns and rows

Three access patterns connect tables, lists and records, and they appear constantly in generated code:

ExpressionReturnsMeaning
Payroll[Gross]ListThe Gross column as a list
Payroll{0}RecordThe first row
Payroll{0}[Gross]ValueGross of the first row
Payroll{[Employee="E-104"]}RecordThe row whose Employee is E-104 (must be unique)
Excel.CurrentWorkbook(){[Name="Payroll"]}[Content]TableThe row named Payroll, then its Content field

The last line is the Source step Power Query writes for From Table/Range: Excel.CurrentWorkbook() returns a table of all tables in the workbook, {[Name="Payroll"]} picks a row by key, and [Content] takes the field that holds the table. Navigation steps in workbook, database and folder queries follow the same pattern.

Power Query M
let
    Payroll = Excel.CurrentWorkbook(){[Name="Payroll"]}[Content],
    TotalGross = List.Sum(Payroll[Gross]),
    WithShare = Table.AddColumn(Payroll, "Share", each [Gross] / TotalGross, Percentage.Type)
in
    WithShare
A step can be a single number (TotalGross) and be reused by a later step. This share-of-total needs no Group By or merge.
ABC
1EmployeeDeptGross
2E-101HR3200
3E-102IT4100
4E-103IT3900
5E-104Sales2800

Before: the Payroll table.

ABCD
1EmployeeDeptGrossShare
2E-101HR320022.9%
3E-102IT410029.3%
4E-103IT390027.9%
5E-104Sales280020.0%

After: each employee's share of total gross (14,000), shown with a percentage format.

Functions, each and the underscore

A function is written (parameters) => expression. (x) => x * 2 doubles a number; (net, rate) => net * (1 + rate) adds VAT. Many library functions take a function as an argument: Table.SelectRows takes a function that receives a row and returns true or false; List.Transform takes a function applied to each item.

Because one-parameter functions are so common, M has a shortcut: each expression means (_) => expression. The underscore is the parameter. And when the parameter is a record, [Gross] on its own is short for _[Gross]. So these three lines are identical:

Power Query M
Table.SelectRows(Payroll, (row) => row[Gross] > 3500)
Table.SelectRows(Payroll, (_) => _[Gross] > 3500)
Table.SelectRows(Payroll, each [Gross] > 3500)
each is syntactic sugar for a function with one parameter called _.

In a list function, _ is the item itself: List.Select(Amounts, each _ > 1000). In a table function, _ is the row record. In Group By (see Group By: totals, counts and the All Rows trick), _ is the small table of the group.

Watch out. Nested each expressions hide the outer underscore: inside an inner each, _ and [Field] refer to the inner item. When you need values from both levels, give at least one function a real parameter name, as in (r) => r[Amount] > [Limit].

Writing a query from scratch

Create a blank query (Data › Get Data › From Other Sources › Blank Query), open the Advanced Editor and type a full query. This one builds a small lookup table without any source, useful for VAT rates or mapping tables that belong to the logic rather than to the data:

Power Query M
let
    // VAT rates by country, maintained in code
    Rates = #table(
        type table [Country = text, VAT = number],
        {
            {"GR", 0.24},
            {"DE", 0.19},
            {"PT", 0.23},
            {"NL", 0.21}
        }
    )
in
    Rates
#table with a typed column definition creates a table with proper data types.

Finding functions

  • Type = #shared in a blank query's formula bar to list every function and value available, then convert the record to a table and filter it, for example names starting with Text..
  • Type a function name without parentheses, such as = Text.PadStart, to see its documentation and an Invoke button.
  • Learn from the UI: click a button, then read the formula bar. Column From Examples is especially good at showing which Text and Date functions exist.
LibraryTypical functions
TableSelectRows, AddColumn, Group, NestedJoin, Combine, TransformColumns, Sort
ListSum, Max, Distinct, Select, Transform, Contains, Dates, Accumulate
TextTrim, Upper, Contains, Split, Combine, PadStart, BeforeDelimiter
NumberFrom, Round, Mod, IntegerDivide
DateYear, Month, AddMonths, StartOfMonth, EndOfMonth, DayOfWeek, ToText
RecordField, FieldNames, AddField, ToTable
Tip. When a generated step lists column names, such as Table.TransformColumnTypes or Table.SelectColumns, think about whether the list should be fixed or computed. Table.ColumnNames(Source) returns the current names as a list, which lets you write steps that adapt to new columns.

Check yourself

1. What does the expression after in determine?

2. What is {10, 20, 30}{1}?

3. What type does Payroll[Gross] return?

4. each [Gross] > 3500 is short for…

5. Which mistake causes a syntax error in a let block?