Query Folding

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 10 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Mastering Query Folding in Semantic Models

Introduction to Query Folding

In the world of data engineering and business intelligence, the performance of your semantic model is often the difference between a tool that empowers users and a tool that frustrates them. One of the most critical, yet frequently misunderstood, concepts in Power BI and Power Query is "Query Folding." At its simplest, query folding is the process where the transformations you apply in Power Query are converted into a single, optimized SQL query that is sent to the source database. Instead of pulling millions of rows into your local machine or the Power BI engine to perform filtering, sorting, or grouping, the database engine does the heavy lifting.

Why does this matter? When query folding works effectively, your data refreshes are lightning-fast because the database only returns the precise, filtered dataset required for your report. When it fails, you are essentially "importing" the entire contents of your tables, performing the transformations in memory, and discarding the unnecessary data. This leads to slow refreshes, high memory consumption, and potential timeout errors. Understanding how to control and verify query folding is a mandatory skill for any professional working with semantic models.

Not read yet

How Query Folding Works Under the Hood

To understand query folding, you must view Power Query as a translator. When you connect to a relational database like SQL Server, Snowflake, or PostgreSQL, Power Query acts as an intermediary. As you click buttons in the user interface—such as "Filter Rows," "Remove Columns," or "Group By"—Power Query builds a script in the M language. However, it also maintains an internal representation of your steps.

If the source database supports the operations you are performing, Power Query attempts to map your M steps directly into the native query language of that source (usually SQL). For example, a "Filter Rows" step translates to a WHERE clause, and a "Remove Columns" step translates to a SELECT statement containing only those specific columns. If the sequence of steps remains "foldable," the final request sent to the database is a highly optimized SQL statement.

Callout: The "Push-Down" Concept Query folding is essentially a "push-down" operation. You are pushing the computational burden of data processing down to the source system. Relational databases are designed specifically to handle complex joins, aggregations, and filtering at massive scale using indexes. By leveraging these engines, you avoid the overhead of moving data over the network and processing it in a single-threaded environment like a local desktop.

Not read yet

Identifying When Query Folding Occurs

The Power Query Editor provides a visual indicator to help you track folding. In the "Applied Steps" pane on the right-hand side, you can right-click any step. If the option "View Native Query" is enabled (not greyed out), it means that the step, along with all preceding steps, is successfully folding. If the option is disabled, it means the chain of folding has been broken at that point.

The Anatomy of a Foldable Sequence

Not every transformation can be folded. The database must support the specific logic you are trying to implement. Common operations that fold include:

  • Column Selection: Choosing only the columns you need.
  • Filtering: Using row-level filters (e.g., date ranges, status codes).
  • Sorting: Applying an ORDER BY clause.
  • Renaming: Changing column headers (often handled via AS aliases in SQL).
  • Simple Aggregations: Grouping by columns and calculating sums, averages, or counts.
  • Joins: Merging queries (when both are from the same source).

The "Breaking" Point

The moment you introduce a transformation that the source database cannot translate into SQL, the folding stops. For example, if you perform a complex transformation in M—such as a custom function that uses external APIs or specific list-based operations that don't map to SQL logic—the engine must pull the data locally to perform the work. Once a step breaks the fold, every subsequent step is performed locally in the Power Query engine, regardless of whether those subsequent steps could have been folded on their own.

Not read yet

Practical Examples of Folding and Non-Folding Transformations

To master this, you need to see the difference between operations that play nicely with SQL and those that do not.

Example 1: Efficient Filtering (Foldable)

Imagine you have a Sales table with 50 million rows. You only need the data for the year 2023.

  1. Operation: Right-click the OrderDate column and select "Date Filters" -> "After" -> 2022-12-31.
  2. SQL Translation: SELECT * FROM Sales WHERE OrderDate > '2022-12-31'
  3. Result: The database scans the index on OrderDate and returns only the rows for 2023. The network traffic is minimal, and the refresh is fast.

Example 2: The "Broken" Fold (Non-Folding)

Now, imagine you want to filter based on a custom calculation that isn't native to SQL.

  1. Operation: You add a custom column using Text.Middle or a complex List.Contains operation to filter rows.
  2. Result: Because the database engine doesn't know how to execute that specific M-based custom function, Power Query must download the entire Sales table into memory first. Only after the data is local can the engine apply your custom filter.

Note: Always place your most restrictive filters as early as possible in your Applied Steps. By reducing the volume of data early, you minimize the amount of data that needs to be processed, even if you eventually perform a non-folding operation later in the chain.

Not read yet

Strategies for Maintaining Query Folding

Maintaining query folding requires a disciplined approach to how you structure your Power Query scripts. It is not just about the operations you use, but the order in which you use them.

1. Reorder Steps Carefully

If you have a foldable step (like filtering) that is currently located after a non-foldable step (like a complex custom function), move the filter up. By moving the filter earlier in the list, you ensure that the database performs the heavy filtering before the data is ever pulled into your model.

2. Avoid Native SQL Queries Where Possible

It is tempting to write your own SELECT * FROM ... query as the source. While this works, it often prevents Power Query from "folding" subsequent steps onto that query. If you write a complex SQL query in the source step, Power Query treats that as a "black box" and often cannot append further logic (like WHERE clauses) to it. Instead, connect to the table directly and use the Power Query UI to perform transformations.

3. Use Database Views

If you find that your transformations are too complex to fold, move the logic into a database view. Create a View in your SQL database that performs the joins, aggregations, and calculations. Then, connect Power Query to that View. This is the ultimate "query folding" strategy because the database does the work before the data even reaches your BI tool.

Not read yet

Comparison: Query Folding vs. Local Processing

Feature Query Folding Local Processing
Execution Location Source Database (SQL) Power BI Engine (RAM/CPU)
Data Volume Only required rows/columns Full dataset transfer
Performance High (utilizes indexes) Low (bottlenecked by network/RAM)
Scalability Excellent for large datasets Limited by local hardware
Complexity Requires standard SQL operations Allows custom M functions

Common Pitfalls and How to Avoid Them

Even experienced developers fall into traps that silently degrade performance. Here are the most frequent mistakes:

The "Add Custom Column" Trap

Adding a custom column using the Add Custom Column button is a frequent culprit. If you use a simple formula like [ColumnA] + [ColumnB], it will often fold. However, if you use a function like Date.ToText or any function that doesn't have a direct SQL equivalent, the folding will break. Always check the "View Native Query" option after adding a custom column to ensure you haven't inadvertently triggered a local import.

The "Merge" Problem

Merging two tables is a powerful feature, but it only folds if both tables reside on the same data source. If you merge a SQL Server table with an Excel file, the merge cannot be folded. The engine must pull both tables into memory to perform the join. If you must join local data with cloud data, try to perform the join in the database first if possible, or accept that this step will be the end of your folding chain.

Data Privacy Levels

Sometimes, query folding fails because of "Data Privacy" settings. If your model connects to two different data sources (e.g., SQL Server and a Web API), Power BI may restrict the ability to send data from one source to another for security reasons. This can prevent folding. Ensure your privacy levels are configured correctly (e.g., setting both to "Organizational") to allow the engine the flexibility to optimize the queries.

Warning: Be cautious when using "Change Type" steps. While usually harmless, changing the data type of a column early in the process is best practice. However, if you change types after a series of transformations, it can sometimes prevent folding depending on the specific database driver being used. Always keep your "Change Type" steps at the very end of your query unless necessary.

Not read yet

Advanced Techniques: Monitoring and Debugging

When you suspect your model is slow, you need to verify if folding is actually happening. Relying on the "View Native Query" option is the first step, but it is not always 100% accurate for complex scenarios.

Using SQL Server Profiler

If you are using SQL Server, you can use the SQL Server Profiler (or Extended Events) to watch the actual queries being sent to the database. This is the "source of truth." If you see a simple SELECT * followed by a massive data transfer, you know your folding has broken. If you see complex SELECT statements with WHERE, GROUP BY, and JOIN clauses, you know your model is optimized.

The "Step-by-Step" Verification

If you have a long list of transformations, perform a binary search to find the culprit:

  1. Disable half of your steps (using the "Extract Previous" or "Disable Load" features).
  2. Check if the "View Native Query" option is available.
  3. If it is, the break is in the second half. If it isn't, the break is in the first half.
  4. Repeat until you isolate the exact step that forces the local import.

Not read yet

Best Practices for Semantic Model Maintenance

To ensure your semantic models remain performant over the long term, adhere to these industry-standard practices:

  • Filter Early and Often: Always apply filters for dates, regions, or categories as the very first steps in your query.
  • Remove Unnecessary Columns: Never import columns you do not need. Every column adds to the memory footprint.
  • Prefer Native Transformations: Use the built-in buttons (Filter, Sort, Group By) rather than writing custom M code whenever possible.
  • Use Database Views: When logic becomes too complex for the Power Query UI to fold, move that logic to the database layer as a View or Stored Procedure.
  • Monitor Data Sources: Regularly check the "View Native Query" status of your most important tables, especially after adding new transformations.
  • Keep M Clean: Avoid overly complex M scripts if the same result can be achieved through a simple SQL view. M is powerful, but it is not a replacement for a well-indexed database.

Not read yet

Frequently Asked Questions (FAQ)

Q: Does query folding work with all data sources? A: No. Query folding is primarily supported by relational databases (SQL Server, Oracle, PostgreSQL, Snowflake). It does not work with flat files (CSV, Excel) or many semi-structured APIs because those sources do not have a query engine that can process SQL.

Q: If "View Native Query" is greyed out, is my model broken? A: Not necessarily. It just means that the step you are looking at cannot be translated into a single SQL statement. If the dataset is small, this may not impact performance. However, for large datasets, this is a major performance bottleneck.

Q: Can I force query folding? A: You cannot "force" it if the operation is fundamentally unsupported. However, you can often "rewrite" your steps to be more foldable. For example, instead of using a complex custom function to parse a date, use the built-in "Date" transformation buttons in the ribbon, which are more likely to be recognized by the folding engine.

Q: Does query folding happen during the refresh or during report interaction? A: Query folding happens during the "Data Refresh" process. When you hit "Refresh" in Power BI, the Power Query engine connects to the database, executes the folded query, and pulls the resulting dataset into the model.

Not read yet

Summary: Key Takeaways for Success

Implementing semantic models requires a deep understanding of how data moves from the source to the report. Query folding is your primary lever for controlling this flow. By ensuring that your transformations happen at the database level, you create models that are faster, more stable, and easier to maintain.

  1. Folding is Efficiency: Query folding moves the computational load to the database, which is built to handle it. This reduces network traffic and memory usage significantly.
  2. Use the UI Wisely: The "View Native Query" indicator is your best friend. Use it frequently to monitor the health of your transformation chain.
  3. The "Breaking" Point Matters: Once a fold is broken by an unsupported operation, the rest of the transformation chain will be performed locally. Keep your most complex, non-foldable logic at the very end of your script.
  4. Database Views are Superior: When logic is too complex to fold, stop trying to force it in Power Query. Create a View in your database and let the SQL engine handle the complexity.
  5. Data Volume Management: Always filter for only the rows and columns you need as early as possible. This is the single most effective way to improve performance regardless of whether folding is active.
  6. Avoid Over-Engineering M: While Power Query's M language is powerful, it is not always the most efficient place to perform data transformations. Know when to delegate to the database.
  7. Test and Verify: Use profiling tools to see what is actually happening at the database level. Don't rely on assumptions; verify the performance of your refreshes to ensure your model scales as your data grows.

By following these principles, you move from being a user of Power Query to an architect of high-performance semantic models. Focus on the data source's capabilities, keep your transformations simple, and always prioritize the database's ability to filter and aggregate before the data reaches your local environment.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.