Sub topic 2
Query folding: the requirement behind incremental refresh
This chapter assumes you can build queries in the Power Query Editor and read the Applied Steps pane. It also assumes you know how Import mode differs from DirectQuery, and that you have a relational source such as SQL Server or Azure SQL Database with a large fact table. You don't need the RangeStart and RangeEnd parameters yet. The next chapters build them. This chapter explains why they only work well when the filter they drive can be pushed down to the source.
What query folding is
Power Query is a transformation engine, called the mashup engine, that runs your M steps. For many sources it doesn't run every step itself. It translates a run of steps into one native query, for example a SQL SELECT statement, and sends that query to the source. The source does the filtering, column selection, and grouping. Only the result comes back to Power Query. This translation is called query folding. The steps are said to fold into the source query.
When a step can't be translated, the engine downloads the data produced so far and runs that step and all later steps locally. Two properties of folding matter here:
- Folding is decided step by step, from the top of the Applied Steps list down.
- Once a step fails to fold, no later step folds. Everything after it runs in the mashup engine, even steps that would fold on their own.
Compare these two queries. Both return the same rows. The first does its work in the database. The second does it on the machine that runs the refresh.
let
Source = Sql.Database("myserver.database.windows.net", "SalesDb"),
FactSales = Source{[Schema = "dbo", Item = "FactSales"]}[Data],
Filtered = Table.SelectRows(
FactSales,
each [OrderDate] >= #datetime(2020, 1, 1, 0, 0, 0)
and [OrderDate] < #datetime(2020, 2, 1, 0, 0, 0)
)
in
Filteredlet
Source = Sql.Database("myserver.database.windows.net", "SalesDb"),
FactSales = Source{[Schema = "dbo", Item = "FactSales"]}[Data],
Buffered = Table.Buffer(FactSales),
Filtered = Table.SelectRows(
Buffered,
each [OrderDate] >= #datetime(2020, 1, 1, 0, 0, 0)
and [OrderDate] < #datetime(2020, 2, 1, 0, 0, 0)
)
in
FilteredTable.Buffer loads the whole table into memory and stops folding. In the second query the Filtered step runs locally, after every row of FactSales has crossed the network.
Why incremental refresh depends on folding
The previous chapter described the cost of a full refresh: every refresh reads the whole table. Incremental refresh avoids that by splitting the table into date-based partitions and refreshing only the recent ones. It does this through a date filter on the table, and the service sends that filter once per partition.
Each partition has its own date boundaries. During refresh, the service substitutes those boundaries for RangeStart and RangeEnd and runs the query for that partition. The design assumes the filter reaches the source as a WHERE clause. Each partition query then returns only its own slice.
If the filter doesn't fold, each partition query still reads the entire table. The mashup engine then throws away every row outside that partition's range. With N partitions in the refresh, the source is read N times in full. That can be slower and more expensive than the full refresh you were trying to avoid. The refresh produces correct data, so it fails silently on cost. You only notice that it's slow, that the source is busy, or that refresh times didn't drop.
Which sources and steps fold
Folding needs a source that has a native query language and a connector that can generate it. Relational sources such as SQL Server, Azure SQL Database, Azure Synapse, Oracle, PostgreSQL, and Snowflake generally fold. Flat files, such as CSV and Excel workbooks, and many web-based sources don't, because there is no engine on the other end to run a query. You can still define a refresh policy over such a source, but each partition then reads all the data. Incremental refresh is designed for relational sources.
Within a foldable source, the connector decides which steps it can translate. The table lists common cases. Exact behavior varies by connector and version, so treat it as a guide and verify in your own query.
| Step type | Usually folds? | Notes |
|---|---|---|
| Filter rows (`Table.SelectRows`) with comparisons | Yes | Comparisons on a column and a constant or parameter translate to `WHERE`. |
| Remove or select columns | Yes | Becomes the `SELECT` list. |
| Rename columns | Yes | Becomes column aliases. |
| Sort rows | Yes | Becomes `ORDER BY`. |
| Keep top rows | Yes | Becomes `TOP` or `LIMIT`. |
| Group by with common aggregates | Yes | Becomes `GROUP BY`. |
| Merge (join) with another query on the same source | Often | Folds to a join if both queries come from the same source and fold themselves. |
| Change data type | Usually | Becomes a `CAST` for many types. |
| Add index column | No | Index columns generally can't be pushed to the source. |
| `Table.Buffer` | No | It forces a local copy. |
| Custom columns that call functions with no SQL equivalent | No | Depends on the function. |
| Merge or append across different sources | No | The engine has to combine the data locally. |
| Stored procedure or a hand-written native query | No | Later steps usually can't fold. |
Two rules follow from the step-by-step behavior:
- Put the date filter first. If you filter right after the navigation step, the filter is almost certain to fold. If you filter after a step that breaks folding, it won't.
- Put non-folding steps after the filter. Steps like index columns or local calculations are fine after the date filter, because the data they handle is already small. Only the order matters.
Checking whether a step folds
Power Query gives you a direct way to test a step:
- In the Power Query Editor, select the step in Applied Steps.
- Right-click it and look at View Native Query.
- If the option is enabled, click it. The dialog shows the SQL that the source receives for the query up to and including that step.
- If the option is greyed out, that step doesn't fold, or an earlier step already broke folding.
For the first query above, the native query has roughly this shape. Column lists and quoting differ by source:
select [_].[OrderID],
[_].[OrderDate],
[_].[CustomerKey],
[_].[SalesAmount]
from [dbo].[FactSales] as [_]
where [_].[OrderDate] >= '2020-01-01T00:00:00'
and [_].[OrderDate] < '2020-02-01T00:00:00'The where clause is what you're looking for. If View Native Query is enabled but the SQL has no where for your date column, the filter was applied after the part that folded.
To find the first step that breaks folding, click through the steps from the top. The last step with View Native Query enabled is the last one that folds. The next step is the cause.
View Native Query shows what can be sent, not what happens at refresh time in the service. For a second check, watch the source. On SQL Server or Azure SQL, use Extended Events, SQL Profiler, or Query Store to see the statements that arrive during a refresh. A folded refresh produces one statement per partition with a date predicate. An unfolded refresh produces statements that select the whole table. The troubleshooting chapter returns to this check.
What the Desktop dialog tells you
When you later configure the refresh policy in Power BI Desktop, the dialog can warn you that it couldn't confirm that the query folds. Treat that warning as a sign that something in the query is wrong. Don't dismiss it. The warning is advisory. The service doesn't block the refresh policy when folding fails, so nothing stops you from publishing a table that reads everything for every partition.
Common ways folding gets lost
Most failures come from a short list of causes:
- Buffering.
Table.BufferorList.Bufferapplied early in the query. - Local-only transformations before the filter. A custom column, index column, or pivot that the connector can't translate, placed above the filter step.
- Combining sources. Appending or merging queries that don't share a source. Check whether the combined query is itself the one you filter. Filter each source query before you combine them.
- Native queries.
Value.NativeQuerywith a hand-writtenSELECT. The source query runs, but steps after it generally don't fold, so a later date filter runs locally. Some SQL connectors let you pass[EnableFolding = true]as the fourth argument so that later steps can fold on top of your SQL. Support depends on the connector, so confirm with View Native Query. A safer option is to move the logic into a database view and connect to the view. - Data type mismatches. Comparing a column to a value of an incompatible type can force a local comparison. The date key variant in a later chapter exists for this reason.
- Privacy levels and firewall rules. When one query refers to another with a different privacy level, the engine may avoid sending data between them, and folding can stop. This depends on your privacy settings, so check it when a query that folds in isolation stops folding after you reference another query.
A practical workflow
Use this order when you prepare any table for incremental refresh:
- Open the table's query and go to the step right after navigation.
- Add a date filter with a literal range, as in the first example, and open View Native Query.
- Confirm the
whereclause appears for your date column. - Add the remaining steps one at a time, checking that View Native Query stays enabled after each.
- If a step breaks folding, move it below the filter, replace it with a foldable equivalent, or move the work into the source as a view.
You then replace the literal dates with RangeStart and RangeEnd, which the next chapters do.
Exercise
A query has these Applied Steps in order: Source, Navigation, Added Index, Filtered Rows (date range). View Native Query is greyed out on Added Index and on Filtered Rows, but enabled on Navigation. What is wrong, and what is the simplest fix that keeps the index column?
Show answer
Added Index doesn't fold, and because folding stops at the first step that fails, the date filter after it also runs locally. Every partition would read the whole table. Move the Filtered Rows step directly after Navigation so it folds, and keep Added Index after it. Then check that View Native Query is enabled on the filter step and that the SQL contains a where clause on the date column.
Exercise
A table has a refresh policy that creates 60 monthly partitions. The date filter doesn't fold. Roughly how many times does the source read the full table during one full refresh of all partitions, and why can this be worse than a normal full refresh?
Show answer
About 60 times, once per partition, because each partition query returns the whole table and the mashup engine discards the rows outside that partition's range. A normal full refresh reads the table once, so an unfolded incremental setup can do much more work and put more load on the source.