Sub topic 15
Query Folding and Keeping Cleaning Fast
This chapter assumes you can connect Power BI Desktop to a source, read the Applied Steps pane, and apply basic cleaning steps such as changing types, removing duplicates, and filtering rows. Here you will learn what query folding is, how to tell whether a step folds, and how to order your cleaning steps so refreshes stay fast.
What query folding is
Query folding is the process where Power Query translates your steps into a single native query, such as SQL, and sends it to the data source. The source does the filtering, grouping, and joining. Power Query receives only the finished result.
Without folding, Power Query downloads the rows and runs each step on your machine, in its own engine. That works, but it is slower and uses more memory, especially for large tables.
Folding mostly applies to sources that have a query engine of their own. Relational databases such as SQL Server are the common case. Flat files such as CSV and most Excel workbooks have no engine to receive a query. Power Query always reads those files in full and processes them locally. The ideas in this chapter still help with files, but you cannot get true folding from them.
Why it matters for cleaning
Cleaning often means removing rows, trimming text, and changing types. Each of these can fold or can break folding, depending on how you do it and where in the sequence it sits.
Folding gives you three benefits:
- Less data crosses the network, because filters run at the source.
- Refreshes finish sooner, because the database is built for sorting and filtering.
- Incremental refresh becomes possible, because it depends on folded date filters.
How the folding pipeline works
Folding is cumulative. Power Query folds steps in order from the top. At the first step that cannot be translated, folding stops. Every later step then runs locally, even if that later step could have folded on its own.
In this example the filter and column removal become one query. The index column cannot be expressed in the folded query, so the trim and type change run locally.
Checking whether a step folds
You do not need to guess. Power BI Desktop gives you two ways to check.
View Native Query
Right-click a step in Applied Steps. If View Native Query is available, the step folds, and clicking it shows the generated SQL. If the option is greyed out, folding has stopped at or before that step.
Check the last step you care about. If View Native Query works there, every step before it folded too.
Query Diagnostics and step indicators
Newer versions of Power BI Desktop also show a folding indicator beside each step in the Applied Steps pane. The indicator shows whether the step folds, does not fold, or cannot be determined. For deeper detail, the Query Diagnostics feature on the Tools tab records what the engine sent to the source and how long each part took.
If the indicators or the right-click option are missing in your version, use View Native Query as your main test.
What usually folds and what usually breaks it
The exact list depends on the source and connector, so treat this table as a guide and verify with View Native Query.
| Step | Usually folds on a SQL source | Notes |
|---|---|---|
| Filter rows (equals, greater than, ranges) | Yes | Filter early. |
| Remove or choose columns | Yes | Reduces data transferred. |
| Rename columns | Yes | Becomes an alias. |
| Change type | Often | Depends on the type and source. |
| Sort rows | Yes | Sorting before a non-folding step is often wasted effort. |
| Group by with standard aggregations | Yes | Sum, count, min, max, average. |
| Merge queries (join) | Often | Both queries must come from the same source. |
| Remove duplicates | Often | Can become DISTINCT. |
| Add index column | Often no | Common folding breaker. |
| Custom columns using M-only functions | No | For example `Text.Proper` on many sources. |
| Pivot and unpivot | Often no | Depends on the connector. |
| Append queries | Often | Sources must be compatible. |
Text cleaning functions are the usual trouble. Text.Trim can fold on some SQL connectors, while Text.Clean and Text.Proper typically do not. Test the specific function on your source instead of assuming.
Ordering steps to keep folding alive
The practical rule is to put the steps that fold first and the steps that break folding last. Because folding stops at the first breaker, a single early breaker can push the whole query into local processing.
Follow this order when you can:
- Connect and navigate to the table.
- Filter rows, especially by date or category, to shrink the data.
- Remove columns you do not need.
- Change types and rename columns.
- Apply steps that probably will not fold, such as text cleanup, custom columns, and index columns.
Reordering steps is safe only when the result stays the same. A filter that depends on a cleaned value, for example filtering on trimmed text, cannot move above the trim. In that case, accept the local work or push the cleaning to the source.
Move the cleaning to the source when you can
If you control the database, the fastest option is often a view that does the cleaning in SQL. Power Query then connects to the view, and the steps you add on top have less to do. Writing a native SQL query in the Source step is another option, but it has a cost, covered next.
Native queries and folding
When you paste your own SQL into the connector, Power Query treats it as a black box. In many cases, later steps cannot fold on top of it, so everything after the Source step runs locally. For some sources, Power BI can still fold later steps over a native query, but you should not rely on that.
Prefer a database view or the regular navigator over a hand-written SQL statement when you want later steps to fold.
Example: checking a M step order
The following query runs without any server, so you can try it. It cannot fold because the source is an in-memory table, but it shows the order of operations you would use against a real database: filter first, then remove columns, then do the cleaning that is unlikely to fold.
let
Source = #table(
{"OrderID", "Region", "Customer", "Amount", "Notes"},
{
{1, "West", " alice smith ", 120, "x"},
{2, "East", "BOB JONES", 80, "y"},
{3, "West", " carol white", 300, "z"}
}
),
FilteredRows = Table.SelectRows(Source, each [Region] = "West"),
RemovedColumns = Table.RemoveColumns(FilteredRows, {"Notes"}),
ChangedType = Table.TransformColumnTypes(RemovedColumns, {{"OrderID", Int64.Type}, {"Amount", type number}}, "en-US"),
CleanedText = Table.TransformColumns(ChangedType, {{"Customer", each Text.Proper(Text.Trim(_)), type text}})
in
CleanedTextAgainst a SQL Server table, you would expect the first three steps after Source to fold and the last step to be the one that might not. You would confirm this by right-clicking ChangedType and CleanedText and checking View Native Query.
Other causes of slow refreshes
Folding is not the only factor. These also slow down cleaning:
- Referencing a query that is not folded. If query B references query A, and A runs locally, B runs locally too. Each query that depends on A may also re-read A's source, unless the data is cached.
- Merging queries from different sources. A join between a database table and an Excel file cannot fold. Power Query must load both sides.
- Privacy levels. If privacy levels conflict between sources, Power Query can block combining them or force extra work. Set levels deliberately instead of turning checks off.
- Wide tables. Removing unneeded columns early is cheap on folded sources and still helps on others.
- Data preview size. The editor previews only a sample of rows. A step can look fast in the editor and still be slow in a full refresh.
Common mistakes
- Assuming a step folds without checking View Native Query.
- Adding an index column or a custom column early, which stops folding for everything below it.
- Sorting at the start of a query that will not fold, which wastes time.
- Using a hand-written SQL statement and then expecting later steps to fold.
- Expecting CSV or most Excel sources to fold.
- Trusting editor speed as a measure of refresh speed.
Summary of the approach
- Know whether your source can fold at all.
- Filter and remove columns first.
- Check the last foldable step with View Native Query.
- Move steps that break folding to the end, or push them into a database view.
- Measure a real refresh instead of judging by the editor preview.
Exercise
A query on a SQL Server table has these steps in order: Source, Added Index, Filtered Rows (Region = "West"), Removed Columns. View Native Query is greyed out on Filtered Rows. What is the most likely cause, and how would you fix it?
Show answer
The Added Index step most likely breaks folding, so every later step, including the filter and column removal, runs locally. Move Filtered Rows and Removed Columns above Added Index so they fold, then add the index last. Confirm by right-clicking Removed Columns and checking that View Native Query is available.
Exercise
You load sales.csv with Csv.Document and filter to one year. A colleague says the filter should fold to the source. Is that correct?
Show answer
No. A CSV file has no query engine to receive a native query, so Power Query reads the whole file and applies the filter locally. You can still filter early to reduce the data kept in later steps, but nothing folds.
Exercise
You paste a custom SQL statement into the Source step of a database connector, and later steps no longer fold. What are two ways to keep the later steps efficient?
Show answer
Replace the statement with a database view and connect to the view through the navigator, so later steps can fold. Alternatively, put the filtering and column selection into the SQL statement itself, so the database returns only the rows and columns you need.