Sub topic 10
Predicate pushdown: filter early, read less
This chapter assumes you can write Polars expressions with pl.col, filter, group_by and with_columns. It also assumes you know what a LazyFrame is and how to read a plan with explain() from the earlier chapters. Here you will learn what predicate pushdown does, when it applies, and what stops it.
What a predicate is
A predicate is an expression that evaluates to true or false for each row. In pl.col("country") == "NO", the predicate decides whether a row survives a filter.
Predicate pushdown is an optimisation. The optimiser moves a filter as close to the data source as it safely can. Ideally the filter moves into the scan node itself. Rows that fail the predicate are then dropped at the source, before later steps such as joins and aggregations see them.
The result must stay identical. The optimiser only moves a filter past a step when doing so cannot change the output.
Seeing it in a plan
The script below creates a small Parquet file so the example runs on its own. It then builds a lazy query that filters after a select.
import polars as pl
pl.DataFrame({
"user_id": [1, 2, 3, 4, 5, 6],
"country": ["NO", "SE", "NO", "DK", "NO", "SE"],
"amount": [10.0, 250.0, 80.0, 120.0, 300.0, 15.0],
}).write_parquet("orders.parquet")
lf = (
pl.scan_parquet("orders.parquet")
.select("user_id", "country", "amount")
.filter(pl.col("country") == "NO")
)
print(lf.explain(optimized=False)) # the filter sits above the scan
print(lf.explain()) # the predicate is part of the scan node
print(lf.collect())In the unoptimised plan, the filter is a separate node above the scan. The scan reads everything and the filter runs afterwards. In the optimised plan, the filter node is gone. The predicate appears inside the scan node, usually labelled as a selection or filter on the scan. The exact wording of the plan text differs between Polars versions, so look for the predicate expression inside the scan node rather than for fixed text.
What a pushed predicate saves
How much a pushed predicate saves depends on the source.
| Source | What pushdown can do |
|---|---|
| Parquet | Skip whole row groups when their min/max statistics prove no row can match. Rows inside the remaining row groups are filtered as they are decoded. |
| CSV | Filter rows while parsing, so rows that fail are never kept in memory. The file is still read and parsed from start to end. |
| In-memory LazyFrame | Evaluate the predicate early, so later steps process fewer rows. |
Parquet gains the most because it stores statistics and splits data into row groups. A filter such as pl.col("ts") > some_date on data sorted by time can skip most of the file. A filter on a column with random values rarely lets Polars skip a row group, because every group's min/max range overlaps the value.
Moving past other steps
The optimiser can push a predicate through many operations, but only when the move is safe. These cases come up often.
selectandwith_columns: a filter on a column that passes through unchanged can move below the step. If the filter uses a column that the step computes, the optimiser must substitute or keep the filter above it.sort: filtering before sorting gives the same rows in the same order and sorts fewer rows.group_by: a filter on a grouping key can move below the aggregation. A filter on an aggregated value cannot, because the value only exists after the aggregation.join: for an inner join, a predicate that uses columns from one side can move to that side. For a left join, only predicates on the left table are safe to move. Moving a right-side predicate below the join would turn unmatched rows into missing values instead of removing them.
The group_by case matters in practice, so here is a runnable check. Both queries give the same answer, and the optimiser can rewrite the first one into the second.
import polars as pl
lf = pl.LazyFrame({
"region": ["EU", "US", "EU", "US", "EU"],
"amount": [5, 7, 9, 11, 13],
})
late = (
lf.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.filter(pl.col("region") == "EU")
)
early = (
lf.filter(pl.col("region") == "EU")
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(late.explain())
print(late.collect().equals(early.collect()))Filtering on total instead would stay above the aggregation in the plan.
What blocks pushdown
A predicate stops moving when moving it could change the result. Watch for these patterns.
- A filter after
head,limitorslice.lf.head(3).filter(...)keeps rows from the first three only.lf.filter(...).head(3)takes the first three matches. The two differ, so Polars cannot reorder them. - A filter on a column produced by a Python UDF. A function inside
map_elementsis opaque to the optimiser. It cannot reason about the function, so a predicate on its output stays above it. - A filter after a window expression. A filter after
pl.col("x").sum().over("g")cannot move below it in general, because removing rows would change the window's result. - Non-deterministic or order-dependent steps. Steps such as
sampleorcum_sumgive different results if the rows before them change.
You can also give the optimiser a better chance by writing the filter yourself where the data enters. For example, if you know a filter does not depend on a computed column, put it before the computation. The optimiser often does this for you, but a hand-written early filter does not depend on its rules.
Checking that it worked
Do not assume that pushdown happened. Check it.
- Call
explain()and look for the predicate inside the scan node. - Compare it with
explain(optimized=False), which shows the plan as you wrote it. If the two plans are the same, no rewriting took place. - If the filter still sits above a node, look at the node directly below it. That node is usually the blocker.
For benchmarking, run the query with the optimiser on and off and compare the times. The switches to turn single optimisations off exist, but their names and the way you pass them have changed between Polars releases, so check the documentation for your installed version before using them.
Summary
Predicate pushdown moves filters toward the data source so that less data is read, kept and processed. It always preserves the result. Parquet benefits most because row group statistics let Polars skip data. Filters move past sorts, selects and, for key columns, aggregations. They stop at slices, window expressions and Python UDFs. Check explain() to confirm the predicate reached the scan.
Exercise
A query reads a Parquet file, calls .head(100), and then filters with pl.col("country") == "NO". A colleague says the optimiser should push the filter into the scan to read less. Why is this wrong, and how would you rewrite the query if you want the first 100 Norwegian rows?
Show answer
The filter comes after head, so it applies only to the first 100 rows of the file. Moving it before head would select the first 100 matching rows, which is a different result, so the optimiser must keep the order. To get the first 100 Norwegian rows, put the filter first: pl.scan_parquet(...).filter(pl.col("country") == "NO").head(100). The predicate can then be pushed into the scan, and the slice can stop the read early.
Exercise
You run explain() on a query and the filter still appears above a map_elements step, not inside the scan node. The filter is on the column that map_elements produced. What are two ways to get pushdown?
Show answer
First, replace the Python function with native expressions such as arithmetic or when/then/otherwise, so the optimiser can see through the step. Second, if the filter can be written on a source column, move it before the map_elements step. Then confirm with explain() that the predicate appears in the scan node.