Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Power Query

Understanding the M Let Expression: Structuring Multi-Step Transformations with Named Variables and In Expressions

Every Power Query transformation you've ever built lives inside a let expression — but most people never learn how it actually works. This lesson teaches you the anatomy, the evaluation model, and the practical patterns that turn M code from a mystery into a tool you control.

🌱 Foundation15 min readNov 29, 2026Updated Nov 29, 2026
Understanding the M Let Expression: Structuring Multi-Step Transformations with Named Variables and In Expressions
On this page
  • Introduction
  • Prerequisites
  • What Is a `let` Expression?
  • The Simplest Possible Example
  • Applying `let` to Real Table Transformations
  • Writing a `let` Expression from Scratch
  • Understanding Variable Scope
  • Nesting `let` Expressions
  • Naming Conventions and Readability
  • The `in` Clause Is More Powerful Than It Looks
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Understanding the M Let Expression: Structuring Multi-Step Transformations with Named Variables and In Expressions

Introduction

Imagine you're handed a raw sales export from your company's CRM. The dates are stored as text in an inconsistent format, the revenue column is mixed with currency symbols, the region codes need to be mapped to full names, and you need to calculate a running margin percentage before the data is usable. That's four distinct transformation steps — and in Power Query, you need a way to chain them together cleanly, give each step a name, and hand the final result off to your data model.

That's exactly what the M let expression does. It's the backbone of almost every query you'll ever write in Power Query. Every time you use the graphical interface to add a step in the Applied Steps pane, Power Query is silently writing a let expression behind the scenes. When you open the Advanced Editor and see that cascade of named steps, you're looking at a let expression in its full form. Understanding this structure — deeply, not just superficially — is the difference between someone who clicks through the UI and someone who can write, debug, and optimize M queries with genuine confidence.

By the end of this lesson, you'll understand not just the syntax of let expressions, but why they're structured the way they are, how named variables flow from one step to the next, what the in clause actually means, and how to write clean, maintainable multi-step transformations from scratch.

What you'll learn:

  • The anatomy of a let expression: bindings, variables, and the in clause
  • How to name intermediate steps and reference them in subsequent steps
  • Why M evaluates expressions the way it does, and what that means for your query structure
  • How to write readable, well-structured let expressions by hand
  • Common pitfalls when nesting or chaining let expressions

Prerequisites

You should have a basic familiarity with what Power Query is and how to open the Advanced Editor. If you've never written M code before, spend a few minutes with M Language Fundamentals: Syntax, Types, and Expressions for Power Query before continuing — this lesson assumes you know what a function call looks like and understand that M works with types like text, number, date, and table.


What Is a `let` Expression?

Before we look at any code, let's build intuition with an analogy.

Think of a recipe. A good recipe doesn't tell you to do everything in one sentence. It breaks the process into named, ordered steps: "Mix the dry ingredients. Combine the wet ingredients. Fold wet into dry. Bake at 375°F." Each step has a name, each step builds on what came before, and the final step is what you actually serve.

A let expression works exactly the same way. It lets you define a series of named intermediate values — in any order, though conventionally top to bottom — and then specifies which of those values is the actual result of the whole expression.

The general structure looks like this:

let
    Step1 = some expression,
    Step2 = another expression that uses Step1,
    Step3 = yet another expression
in
    Step3

The let keyword opens the block. Each line inside defines a binding: a name on the left, an equals sign, and an expression on the right. Bindings are separated by commas. The in keyword closes the binding section and introduces the return expression — the single value that the entire let expression evaluates to.

Key insight

The in clause doesn't have to reference the last binding. It can reference any binding defined in the let block, or even be a completely new expression that uses any of the named variables. It just has to be a single valid M expression.


The Simplest Possible Example

Let's start with something deliberately minimal before we tackle realistic data.

let
    BasePrice = 100,
    TaxRate = 0.08,
    TaxAmount = BasePrice * TaxRate,
    TotalPrice = BasePrice + TaxAmount
in
    TotalPrice

Walk through this step by step:

  1. BasePrice is bound to the number 100.
  2. TaxRate is bound to 0.08.
  3. TaxAmount references both of those — it multiplies them to get 8.
  4. TotalPrice adds BasePrice and TaxAmount to get 108.
  5. The in clause says: the result of this whole expression is TotalPrice, which is 108.

This is a valid, complete M query. If you paste it into the Advanced Editor in Power Query, it evaluates to 108. The names BasePrice, TaxRate, TaxAmount don't appear in the output — they exist only inside the let block as scaffolding for the computation.


Applying `let` to Real Table Transformations

The power of let becomes obvious when you're working with tables. Every step you create in the graphical Power Query editor corresponds to a binding in a let expression. Let's look at what Power Query actually generates when you do three simple transformations in the UI.

Suppose you load a CSV file, rename a column, and filter a row. Open the Advanced Editor and you'll see something like this (simplified):

let
    Source = Csv.Document(File.Contents("C:\Sales\Q4_sales.csv"), [Delimiter=",", Encoding=65001]),
    PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    RenamedColumns = Table.RenameColumns(PromotedHeaders, {{"rev", "Revenue"}}),
    FilteredRows = Table.SelectRows(RenamedColumns, each [Region] = "North")
in
    FilteredRows

Each binding takes the result of the previous binding as its first argument. PromotedHeaders wraps Source. RenamedColumns wraps PromotedHeaders. FilteredRows wraps RenamedColumns. The in clause returns FilteredRows.

This is a chain — and the naming of each step is what makes it readable and debuggable. If something goes wrong, you can temporarily change the in clause to reference an earlier step and see the data at that point in the pipeline.

Tip

Temporarily changing in StepName to an earlier binding is one of the most useful debugging techniques in Power Query. It lets you inspect intermediate results without breaking your query structure.


Writing a `let` Expression from Scratch

Let's work through a realistic scenario end-to-end. You have a list of sales records. The SaleDate column is stored as text in the format "2024-03-15", the Revenue column contains strings like "$1,250.00", and you need to output a clean table with proper types and a calculated Month column.

Here's how you'd build this let expression step by step:

let
    // Raw data — in practice this comes from a Source step
    RawData = Table.FromRecords({
        [SaleDate = "2024-03-15", Rep = "Alicia Marsh",    Revenue = "$1,250.00"],
        [SaleDate = "2024-04-02", Rep = "Marcus Bell",     Revenue = "$890.00"],
        [SaleDate = "2024-04-18", Rep = "Priya Sundaram",  Revenue = "$3,400.00"],
        [SaleDate = "2024-05-01", Rep = "Marcus Bell",     Revenue = "$710.50"]
    }),

    // Clean the Revenue column: strip "$" and "," then convert to number
    CleanRevenue = Table.TransformColumns(RawData, {
        {"Revenue", each Number.FromText(Text.Remove(_, {"$", ","})), type number}
    }),

    // Parse the SaleDate column from text to date
    ParsedDates = Table.TransformColumns(CleanRevenue, {
        {"SaleDate", each Date.FromText(_, "en-US"), type date}
    }),

    // Add a Month column derived from SaleDate
    WithMonth = Table.AddColumn(ParsedDates, "Month", 
        each Date.ToText([SaleDate], "MMMM yyyy"), type text),

    // Reorder columns for a clean final output
    FinalTable = Table.SelectColumns(WithMonth, {"SaleDate", "Month", "Rep", "Revenue"})
in
    FinalTable

Notice a few things:

Each step has a descriptive name. CleanRevenue, ParsedDates, WithMonth — these names communicate intent. Someone reading this query six months from now (possibly you) will immediately understand what each step does without having to decode the function call.

Each step references the previous step. CleanRevenue takes RawData as input. ParsedDates takes CleanRevenue. This creates a clear dependency chain.

Comments are allowed. The // syntax marks single-line comments. Use them generously in complex queries.

Note

M is a functional language, which means expressions don't modify data in place — they always produce new values. Each binding in a let expression is an immutable name-to-value association. You cannot reassign a variable once it's been bound in the same let block.


Understanding Variable Scope

Variable scope in a let expression is an important concept that trips up beginners. Here's the rule: every binding defined in a let block is visible to every other binding in that same block, regardless of the order they appear.

This means you could technically write your bindings out of their logical order:

let
    FinalResult = StartValue * 10,
    StartValue = 5
in
    FinalResult

This is valid M. FinalResult references StartValue, and even though StartValue is defined after FinalResult in the source code, M can resolve it correctly. M uses a lazy evaluation model — it doesn't evaluate bindings in top-to-bottom order; it evaluates whatever is needed to compute the in expression, pulling in dependencies as required.

That said, writing bindings out of logical order is a terrible idea for readability. Convention — and the Power Query UI — always places earlier steps first. Follow that convention.

Warning

Just because M can resolve out-of-order bindings doesn't mean circular references are allowed. If StepA references StepB and StepB references StepA, M will throw an evaluation error. There's no way to resolve circular dependencies in a single let block.

If you want to understand why M's evaluation model works this way at a deeper level, Understanding M Language Query Evaluation: Lazy Evaluation, Dependency Graphs, and Step Ordering in Power Query covers the dependency graph mechanics in detail.


Nesting `let` Expressions

Here's something that surprises many Power Query users: a let expression is itself an expression. That means anywhere M expects an expression — inside a function argument, as the value of a binding, inside a list — you can put a let expression.

This is useful when you want to compute something complex in an isolated context without polluting the top-level namespace of your query. For example:

let
    SalesData = Table.FromRecords({
        [Rep = "Alicia Marsh",   Revenue = 1250, Cost = 800],
        [Rep = "Marcus Bell",    Revenue = 890,  Cost = 600],
        [Rep = "Priya Sundaram", Revenue = 3400, Cost = 2100]
    }),

    WithMargin = Table.AddColumn(SalesData, "MarginPct", each
        let
            GrossMargin = [Revenue] - [Cost],
            MarginPct   = GrossMargin / [Revenue]
        in
            Number.Round(MarginPct, 4)
    , type number)
in
    WithMargin

The inner let expression inside Table.AddColumn computes the margin for each row using GrossMargin as an intermediate variable. This keeps the logic clear and avoids a deeply nested arithmetic expression like Number.Round(([Revenue] - [Cost]) / [Revenue], 4) — which is correct but harder to read and modify.

Tip

Use nested let expressions when a computed column requires more than one intermediate value to calculate. It's far easier to maintain a named intermediate variable than to decode a compound expression six months later.

Nested let expressions also appear naturally when you're writing custom M functions, since the body of a function is itself an expression that can be a let block.


Naming Conventions and Readability

Power Query's auto-generated step names are functional but not beautiful: #"Changed Type", #"Filtered Rows", #"Removed Other Columns". The #"..." syntax is M's way of allowing step names that contain spaces or reserved words.

When you write let expressions by hand, you have full control over naming. Here are conventions that experienced M developers follow:

Use PascalCase without spaces. CleanRevenue, ParsedDates, FinalTable — this avoids the need for #"..." quoting entirely and reads clearly.

Name steps by what they produce, not what they do. FilteredSalesRows is better than FilterStep. The name describes the state of the data after the operation.

Use Source as the first binding. This is a Power Query convention for the step that loads raw data. Sticking to it makes your query consistent with auto-generated code.

Keep the final binding close to what it describes. If your query produces a table, the last binding before in is usually called FinalTable, Output, or simply the name of the entity you're returning.


The `in` Clause Is More Powerful Than It Looks

Beginning M writers often think of the in clause as simply "pick which step to return." But it's more flexible than that. The in clause accepts any expression, not just a variable name.

This means you can write inline logic in the in clause:

let
    SalesTable = Table.FromRecords({
        [Region = "North", Revenue = 50000],
        [Region = "South", Revenue = 32000],
        [Region = "East",  Revenue = 71000]
    }),
    TotalRevenue = List.Sum(SalesTable[Revenue])
in
    "Total revenue across all regions: " & Number.ToText(TotalRevenue)

Here the in clause constructs a text string on the fly using TotalRevenue. This evaluates to "Total revenue across all regions: 153000".

You'd use this less often in a final data model query and more often in a helper calculation or a diagnostic step — but knowing it's possible gives you flexibility.


Hands-On Exercise

Work through this exercise to cement your understanding. You'll build a let expression from scratch that processes a small employee dataset.

The scenario: You have a list of employees with their hire dates as text, their annual salaries as numbers, and their department codes ("ENG", "MKT", "OPS"). You need to produce a table with:

  • Hire dates parsed to the date type
  • A YearsEmployed column (calculated as of January 1, 2025)
  • Department names expanded from codes to full names
  • A SeniorityTier column: "Junior" for less than 3 years, "Mid" for 3–7 years, "Senior" for more than 7 years

Step 1: Start with a Source binding using Table.FromRecords to create your raw dataset with at least four employees.

Step 2: Add a ParsedDates binding that uses Table.TransformColumns to convert the HireDate text column to type date.

Step 3: Add a WithYearsEmployed binding that uses Table.AddColumn to calculate YearsEmployed as Duration.TotalDays(#date(2025,1,1) - [HireDate]) / 365.25, rounded to one decimal place.

Step 4: Add a WithDeptName binding that maps "ENG" → "Engineering", "MKT" → "Marketing", "OPS" → "Operations" using Table.AddColumn with an if-then-else expression.

Step 5: Add a WithSeniority binding that uses another Table.AddColumn with a nested if-then-else to assign the seniority tier based on YearsEmployed.

Step 6: Use Table.SelectColumns in a final binding to output only the columns you care about, in the order you want them.

Step 7: Set your in clause to that final binding.

Paste the entire expression into the Power Query Advanced Editor to verify it evaluates without errors.


Common Mistakes & Troubleshooting

Missing commas between bindings. Every binding except the last must end with a comma. Forgetting one is the single most common syntax error. The error message is usually Token Comma expected and Power Query will highlight the problem area.

Putting a comma after the last binding. The binding immediately before in must not have a trailing comma. This is the reverse of the previous mistake and equally common.

Referencing a variable before it's defined in a circular way. You can reference any variable in any order unless that creates a cycle. If you get an error about circular references, trace your dependency chain.

Using a reserved word as a variable name without quoting. If you accidentally name a binding let, in, each, if, then, else, true, false, or null, M will get confused. Use #"let" to quote it, or better yet, choose a different name.

Forgetting that in returns exactly one value. You cannot return multiple values directly from a let expression. If you need to return multiple things, wrap them in a record [A = ..., B = ...] or a table.

Warning

A very subtle bug occurs when you accidentally shadow a binding name. If you use the same name twice in a let block — say, two bindings both named CleanData — M will not throw an error immediately in some contexts, but the behavior is undefined and unpredictable. Always use unique names for every binding.

For more complex queries, the patterns you've learned here connect directly to building multi-stage ETL pipelines in Power Query M, where let expressions form the structural foundation of each query in a modular chain.


Summary & Next Steps

The let expression is the fundamental organizing structure of M code. Everything you do in Power Query — whether you write it by hand or generate it through the UI — lives inside a let block. Understanding it means understanding:

  • Bindings associate names with values or expressions
  • Each binding can reference any other binding defined in the same let block
  • The in clause determines what the entire expression returns
  • Nested let expressions let you organize complex per-row logic cleanly
  • Descriptive naming makes the difference between a query that's maintainable and one that's a debugging nightmare

This isn't just a syntax lesson — it's a mental model for how to structure transformations. Every time you add a step in Power Query, ask yourself: does this step have a clear name that describes what it produces? Does it do one thing well? Could someone reading this in six months understand the pipeline without documentation?

From here, the natural directions to deepen your M skills include:

  • Exploring how M handles list and record operations inside let expressions, since records and lists often appear as intermediate values in complex pipelines
  • Learning advanced table operations like Group and Join where multi-step let expressions become essential for readability
  • Understanding error handling patterns with try-otherwise so your let expressions handle bad data gracefully in production

The let expression is where everything in M begins. Master it, and the rest of the language becomes accessible.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Advanced M Language

Previous

Implementing Custom Function Memoization and Result Caching in Power Query M: Building Stateless Computation Patterns That Minimize Redundant Evaluations Across Complex Query Graphs

Related Insights

Power QueryFoundation

Replacing Values and Fixing Inconsistent Entries in Power Query: Standardizing Categories, Codes, and Labels

16 min
Power QueryExpert

Implementing Custom Function Memoization and Result Caching in Power Query M: Building Stateless Computation Patterns That Minimize Redundant Evaluations Across Complex Query Graphs

25 min
Power QueryExpert

Implementing Custom Audit Logging and Lineage Tracking in Power Query M: Capturing Row Counts, Source Metadata, and Transformation Timestamps Across Multi-Step ETL Pipelines

25 min

On this page

  • Introduction
  • Prerequisites
  • What Is a `let` Expression?
  • The Simplest Possible Example
  • Applying `let` to Real Table Transformations
  • Writing a `let` Expression from Scratch
  • Understanding Variable Scope
  • Nesting `let` Expressions
  • Naming Conventions and Readability
  • The `in` Clause Is More Powerful Than It Looks
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps