Using variables while creating custom columns in Power Query

Problem Statement: How to create or use variables while creating custom columns in Power Query

In modern data analytics workflows, Power Query, part of Microsoft’s Power BI, Excel, and Fabric ecosystem, serves as a cornerstone for data transformation (ETL). Within Power Query’s M language, using variables effectively enables BI developers and data engineers to create reusable, readable, and optimized transformation logic.
Variables in Power Query are not traditional programming variables that store mutable state; instead, they represent immutable named expressions that simplify complex queries, reduce redundancy, and enhance performance.

When creating custom columns or advanced transformations in Power Query, leveraging variables makes your M code modular and maintainable, especially in large enterprise datasets where query logic can grow intricate. This approach aligns with best practices for Power BI development, emphasizing transparency, scalability, and documentation within the Power Query Editor.

Solution:

To declare variables in power query, let and in keywords are used.

The let…in construct forms the backbone of the M language syntax. It allows you to define multiple intermediate expressions (variables) inside a let block and then return a final computed result with the in keyword. This is similar to defining local variables or temporary expressions in functional programming languages like F#, from which M derives many of its concepts.

Typical syntax structure:

let

    VariableName1 = <Expression1>,

    VariableName2 = <Expression2>,

    FinalResult = <SomeTransformationUsingVariables>

in

    FinalResult

A comma separates each line in the let block, and all variables are evaluated lazily, meaning Power Query only computes them when they’re referenced. This improves performance by avoiding unnecessary recalculations, which is crucial for large datasets in Power BI or Fabric dataflows.

When creating custom columns, variables allow you to:

  • Avoid repeating the same calculation logic.
  • Improve readability for business analysts.
  • Facilitate debugging by isolating logic into named expressions.
  • Optimize query folding where applicable (especially when querying SQL, Dataverse, or OData sources).

Scenario 1: In the below example, in a calculated column simple calculation is performed where the addition of three numbers is shown using variables.

M code is as follows:

Let’s illustrate with an M expression that adds three constants using defined variables:

let

    a = 10,

    b = 20,

    c = 30,

    result = a + b + c

in

    result

In this case:

  • a, b, and c act as variables.
  • The final expression result combines their values.
  • The computation is executed once and efficiently returned.

This example might seem trivial, but it introduces a key principle: Power Query evaluates from top to bottom, binding each name to its result before the final expression.
Such an approach scales elegantly when these variables represent columns or transformations derived from a dataset.

For instance, in a dataset transformation scenario, you could replace constants with column references or aggregations, such as:

let

    Source = Excel.CurrentWorkbook(){[Name=”Sales”]}[Content],

    CustomColumn = Table.AddColumn(Source, “Total”, each [Price] + [Tax] + [Discount])

in

    CustomColumn

Using variables, you could refactor this to:

let

    Source = Excel.CurrentWorkbook(){[Name=”Sales”]}[Content],

    AddTotal = Table.AddColumn(Source, “Total”,

        each

            let

                base = [Price],

                tax = [Tax],

                discount = [Discount],

                total = base + tax + discount

            in

                total

    )

in

    AddTotal

This method ensures readability, maintainability, and traceability of business logic within Power Query transformations, essential for enterprises implementing data governance and version control for BI assets.

Scenario 2: In the example below, in the Sales table, there are two columns, which are Unit Price and Quantity. In a single calculated column, the sales value is calculated, and whether the sale is above 2000 or below is mentioned using variables.

M code is as follows:

Here’s a practical enterprise-style example demonstrating business logic encapsulated with variables:

let

    Source = Excel.CurrentWorkbook(){[Name=”Sales”]}[Content],

    AddSalesCategory = Table.AddColumn(Source, “Sales Category”,

        each

            let

                unitPrice = [Unit Price],

                quantity = [Quantity],

                salesValue = unitPrice * quantity,

                category = if salesValue > 2000 then “Above 2000” else “Below 2000”

            in

                category

    )

in

    AddSalesCategory

This code calculates each row’s sales value dynamically and categorizes it based on a threshold. The structure improves clarity for data professionals and ensures easier debugging if future business rules (for instance, thresholds or discount logic) change.

In a Power BI Service or Fabric Dataflow, such transformations become part of the organization’s semantic layer, enabling reusability across multiple reports.

Multiple variables can be created in Power Query for computing different calculations.

The ability to declare and reuse multiple variables makes Power Query not only a data transformation tool but a lightweight functional programming environment within Power BI. This feature is pivotal when designing robust ETL processes that transform raw data into analytical models.

Why Variables Matter in Enterprise Power BI Development

  1. Performance Optimization:
    Power Query’s lazy evaluation ensures that variables are only computed when needed. This minimizes memory consumption and speeds up transformations, particularly when applied to large SQL or data lake sources.
  2. Code Maintainability:
    Variables simplify complex expressions, making Power Query M code easier to maintain and audit. This is especially useful when BI teams collaborate using version-controlled environments (Git, DevOps, or Fabric).
  3. Reusability and Scalability:
    Using variables allows developers to implement standardized business logic across multiple dataflows. For example, calculating gross margin, cost of goods sold (COGS), or regional profitability can all reuse the same logic stored as variables.
  4. Error Reduction and Governance:
    By modularizing logic, variables reduce errors during schema updates or data model extensions. Enterprises can enforce M code templates with predefined variable structures—an essential aspect of Power BI governance frameworks implemented by partners like Addend Analytics.

Advanced Use Cases

1. Using Variables in Conditional Transformations:
Variables can simplify nested conditions. For example, a credit scoring model or HR evaluation logic can be made cleaner:

let

    performanceScore = if [KPI] > 85 then “Excellent”

        else if [KPI] >= 70 then “Good”

        else “Needs Improvement”

in

    performanceScore

2. Dynamic Thresholds Using Parameters and Variables:
Combine parameters and variables to create dynamic models:
let

    Threshold = Excel.CurrentWorkbook(){[Name=”Parameters”]}[Content]{0}[Value],

    category = if [Sales] > Threshold then “High” else “Low”

in

    category
3. Complex Aggregations and Grouped Calculations:
Variables help handle grouping logic within the Table. Group transformations, enabling roll-ups of KPIs by region, category, or time.

4. Integration with Power BI Dataflows and Fabric Pipelines:
Variables improve dataflow performance when working with Azure Synapse, Dataverse, or OneLake in Microsoft Fabric, as computations are optimized and query folding is preserved.

Best Practices for Using Variables in Power Query

  • Name variables descriptively – e.g., TotalSalesValue, AdjustedPrice, GrossMargin.
  • Use nested let blocks sparingly for readability.
  • Comment your M code to improve collaboration and governance.
  • Parameterize threshold values for flexibility across environments (Dev, Test, Prod).
  • Leverage Power BI templates with predefined variables to standardize across projects.

By following these best practices, organizations can design resilient, high-performing, and auditable ETL pipelines that support both Power BI and Microsoft Fabric initiatives.

For organizations scaling Power BI enterprise-wide, Power Query variables are a stepping stone toward automated, self-healing data pipelines. With the growing adoption of Microsoft Fabric, Dataflows Gen2, and Direct Lake, mastering variables equips BI teams to design dynamic, reusable transformations that drive consistency across departments.

At Addend Analytics, we integrate these practices into governed BI frameworks that reduce refresh failures, enforce performance optimization, and accelerate ROI from Power BI investments.

Our clients see measurable benefits:

  • 40–60% faster data refresh times
  • 30% reduction in ETL maintenance overhead
  • Improved governance and code standardization across BI teams

We help businesses connect Power Query logic to enterprise data warehouses, ERP systems (like SAP, Dynamics 365, Oracle), and cloud data stores (Azure SQL, Snowflake, Synapse), enabling end-to-end data transformation excellence.

If your organization wants to improve its Power BI data transformation efficiency, implement governed Power Query frameworks, or adopt Microsoft Fabric for scalable analytics, Addend Analytics can help.

Book a Free Consultation Now and learn how we can automate and optimize your Power BI and Power Query development lifecycle.

solutions@addendanalytics.com | +1 (470) 686-6644
Serving USA | UK | Canada | Australia

Facebook
Twitter
LinkedIn

Addend Analytics is a Microsoft Gold Partner based in Mumbai, India, and a branch office in the U.S.

Addend has successfully implemented 100+ Microsoft Power BI and Business Central projects for 100+ clients across sectors like Financial Services, Banking, Insurance, Retail, Sales, Manufacturing, Real estate, Logistics, and Healthcare in countries like the US, Europe, Switzerland, and Australia.

Get a free consultation now by emailing us or contacting us.