Sub topic 15
Reading query plans and optimizations
This chapter assumes you can build a lazy query with scan_csv, filter, group_by and agg, and call collect(). You should also know what an expression is. You do not need to know anything about database internals.
A lazy query is a plan before it is a result. Polars records your steps, rewrites the plan into a cheaper equivalent, and only then runs it. explain() shows you that plan. Reading it lets you check that Polars is doing the work you expect, such as reading only the columns you use.
Setup: a file to scan
The examples below use a small CSV with five columns, of which the query needs only two. The script creates the file, so you can run it as shown.
import polars as pl
pl.DataFrame(
{
"region": ["north", "south", "north", "west", "south"],
"amount": [10, -5, 30, 0, 25],
"product": ["a", "b", "a", "c", "b"],
"rep": ["x", "y", "x", "z", "y"],
"notes": ["", "refund", "", "", ""],
}
).write_csv("sales.csv")
query = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(query.explain(optimized=False))
print(query.explain())
print(query.collect().sort("region"))explain(optimized=False) prints the plan exactly as you wrote it. explain() prints the optimized plan, which is the one Polars runs. The last line runs the query. The sort only makes the printed order stable, because group_by does not promise any row order.
How to read a plan
A plan is a tree of operations printed as indented text. Data flows from the innermost, most indented line outward. Read it from the bottom up: the scan is at the bottom, and the final operation is at the top.
For the query above, the unoptimized plan looks roughly like this:
AGGREGATE
[col("amount").sum().alias("total")] BY [col("region")] FROM
FILTER [(col("amount")) > (0)] FROM
Csv SCAN [sales.csv]
PROJECT */5 COLUMNSThe optimized plan looks roughly like this:
AGGREGATE
[col("amount").sum().alias("total")] BY [col("region")] FROM
Csv SCAN [sales.csv]
PROJECT 2/5 COLUMNS
SELECTION: [(col("amount")) > (0)]Exact wording and layout differ between Polars versions, so look for the ideas, not the strings. Two differences matter here:
PROJECT */5 COLUMNSbecamePROJECT 2/5 COLUMNS. The scan now reads two of the five columns.- The separate
FILTERstep disappeared. The condition now appears asSELECTIONon the scan itself, so rows are discarded as the file is read.
The main optimizations
Polars applies a set of rewrites. Each one gives the same result as the original plan but does less work.
| Optimization | What it does | What to look for in the plan |
|---|---|---|
| Projection pushdown | Reads only the columns the query uses | `PROJECT n/m COLUMNS` with n smaller than m |
| Predicate pushdown | Moves filters as close to the data source as possible | `SELECTION` or a filter placed below other steps |
| Slice pushdown | Stops reading after the rows a `head` or `limit` needs | A slice or row limit on the scan |
| Common subplan elimination | Computes a repeated sub-query once and reuses it | A cache node shared by branches |
| Expression simplification | Folds constants and removes redundant work | Constants already evaluated, for example `2 * 3` shown as `6` |
| Type coercion | Inserts casts so operand types match | `.cast(...)` that you did not write |
Projection pushdown
Polars looks at every column your expressions mention. Anything not mentioned is never read from the file. In the example, product, rep and notes are not used, so the scan skips them. This matters most for wide files, where you might need 3 of 80 columns.
Predicate pushdown
A predicate is a boolean condition, such as amount > 0. Filtering early means later steps, such as grouping and joining, process fewer rows. For some file formats, such as Parquet, Polars can also use file statistics to skip whole chunks of data. CSV has no such statistics, so it still reads each row, but the filter is applied during the read instead of afterwards.
Slice pushdown
If you write pl.scan_csv("big.csv").head(5), Polars can stop reading after enough rows. The optimizer applies this when no earlier step needs the full data.
Common subplan elimination
If two branches of a query start from the same lazy frame, for example a self-join or a concatenation of two filtered views, Polars can compute the shared part once. It does this with a cache node. You see it in the plan as a node that two branches point to.
Seeing what an optimization does
The quickest way to learn this is to compare. Take a query where you change one thing and print both plans.
import polars as pl
lf = pl.scan_csv("sales.csv")
# The filter comes after the aggregation, on a column that is a group key.
late = (
lf.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.filter(pl.col("region") == "north")
)
print(late.explain())
print(late.collect())Here the filter is on region, which is a grouping key. Removing rows of other regions before grouping gives the same answer for the north group, so Polars is able to push this filter down below the aggregation. Look at the printed plan to confirm whether it did in your version.
Now change the filter to pl.col("total") > 20. The total column does not exist until the aggregation has run, so no optimizer can move that filter below it. It must stay above the AGGREGATE. That is a correct plan, not a missed optimization.
When optimizations are blocked
Some code hides information from the optimizer. The most common case is a Python function, such as map_elements or map_batches. Polars cannot see inside it. It does not know which columns the function really reads, or whether it keeps row order or values stable, so it must be cautious. In plans, such steps appear as opaque Python calls, and the rewrites around them may be limited.
Other things that can limit pushdown:
- Reading the data eagerly with
read_csvinstead ofscan_csv. There is no plan to optimize, and the whole file is already in memory. - Calling
collect()in the middle of a pipeline and then continuing with.lazy(). Each query is optimized separately, so a filter later in the code cannot reach back to the first scan. - Filters that depend on non-deterministic or order-sensitive operations, where moving the filter could change the result.
Disabling optimizations for debugging
If a result looks wrong and you suspect an optimization, compare the optimized and unoptimized plans first. Then run the query with optimizations turned off and compare results. collect() accepts flags such as predicate_pushdown=False and projection_pushdown=False. In recent Polars releases these flags are grouped in a QueryOptFlags object passed as optimizations=. Check the documentation for your installed version. If switching one off changes the output, you have found a real bug worth reporting. If not, the cause is in your query logic.
A reading checklist
Use these questions on any plan:
- Which scan is at the bottom, and how many columns does it read?
- Is every filter you wrote either on the scan or as low in the plan as it can go?
- Do any steps appear that you did not write, such as casts? Do they hint at a type mismatch in your data?
- Are there Python calls in the middle? If so, can a native expression replace them?
- Does a cache node appear, and does it match a sub-query you reuse?
Exercise
You run pl.scan_csv("sales.csv").select("region", "amount").filter(pl.col("amount") > 0).explain() on a file with 5 columns. Which two optimizations should you expect to see in the printed plan, and which line shows each one?
Show answer
Projection pushdown, shown as PROJECT 2/5 COLUMNS on the scan, since only region and amount are used. Predicate pushdown, shown as a SELECTION on the scan (or the filter moved down to the scan) with the condition amount > 0, so rows are discarded as the file is read.
Exercise
A query ends with .filter(pl.col("total") > 20), where total was created by an agg. Why can Polars not push this filter below the aggregation?
Show answer
The total column only exists after the aggregation has run. The filter depends on a value that the earlier step produces, so it has to stay above the AGGREGATE node. Moving it below would not even be well defined.