Skip to content

Query Folding

When a query reads a file, such as a CSV, Power Query has to do every transformation itself, because a file cannot do any work. For light steps, such as removing or renaming columns, on files of up to a million rows or so, that is fine.

It becomes a problem with heavier steps on bigger files. To sort ten million rows from a CSV, Power Query has to read every row into memory before it can sort them. It can be done, but it is slow, and there is often a better way.

Query folding is Power Query’s ability to hand steps back to the source to carry out. Where the source is a database, Power Query translates the steps into the database’s own query language, such as SQL, and sends that one query. The database does the filtering, joining or sorting, and only the result comes back.

Power Query folds steps automatically, but only where the source and the steps allow it:

  1. The source must be able to run queries. Most relational databases can, and so can some other sources, such as OData feeds and Analysis Services. Files such as CSV and Excel workbooks cannot.
  2. The connector must support folding. Some ODBC and OLE DB drivers do not, even where the database behind them could.
  3. A hand-written query usually stops it. If the query starts with SQL written by hand, which Power Query calls a native query, the steps after it are not folded in most cases.
  4. A step that cannot fold stops it. Once Power Query reaches a step it cannot translate for the source, it runs that step and the ones after it itself.

The practical lesson is to put the steps that fold, such as filtering rows, removing columns and grouping, before the steps that do not.

Each step of a query is listed under Applied Steps on the right of the editor. Right-click a step and look at View Native Query. If it is available, the step folds, and choosing it shows the query Power Query will send to the source.

If it is greyed out, the step is probably not folding, but that is not certain, because some connectors fold without showing the native query. Power Query Online, which is used for dataflows, is clearer, because it marks each step with an indicator that shows whether it folds.

A more technical check is to wrap the step’s name in the Value.Metadata function in the formula bar, for example:

= Value.Metadata(#"Removed Other Columns")

This returns a record. Where the connector supplies folding details, the record has a QueryFolding field, and inside it an IsFolded field, which is TRUE when the step is folded.