Sub topic 5
Predicate and projection pushdown
This chapter assumes you can write Polars expressions (pl.col, filter, select, with_columns) and that you know the difference between a lazy scan and an eager read from earlier in this tutorial. It explains the two optimizations that decide how much data a lazy query reads at all, before the streaming engine processes any of it.
Why pushdown matters for memory
A lazy query is a description of work. When you call collect or a sink, Polars first rewrites that description into a cheaper one, then executes it. Two of the most useful rewrites move work toward the data source:
- Projection pushdown reads only the columns the query uses.
- Predicate pushdown applies filters during the scan, so rows that fail them are skipped early or never decoded.
Both reduce the amount of data that enters the pipeline. For a larger-than-memory dataset this is often the difference between a query that finishes and one that doesn't. Pushdown does not replace streaming. It shrinks the input that streaming then processes in chunks.
Projection pushdown
Suppose a Parquet dataset has 40 columns, but your query needs user_id and amount. An eager read_parquet loads all 40 columns. A lazy scan loads only the columns that appear anywhere in the query.
Columns used only in a filter still count as needed. If you filter on status and then select user_id and amount, the scan reads three columns: status, user_id and amount.
Parquet is stored by column, so unused columns are never read from disk. CSV is stored by row. Polars can skip parsing unused columns, but it still reads every byte of the file. So projection pushdown saves much more I/O on Parquet than on CSV.
Predicate pushdown
A predicate is a boolean expression that decides which rows to keep, such as pl.col("status") == "ok". With predicate pushdown, Polars hands the predicate to the scan instead of filtering after the scan returns a full table.
For Parquet, this goes beyond filtering early. A Parquet file is split into row groups, and each row group stores statistics such as the minimum and maximum of each column. If a row group's amount maximum is 50 and your predicate is amount > 100, Polars can skip that whole row group without decoding it.
This works best when data is physically organized so that the filtered column varies little within a row group. For example, a file sorted by date makes a date-range filter skip most row groups. A file where dates are scattered randomly gives every row group a wide min/max range, so very little can be skipped.
For CSV there are no statistics. The predicate is applied while rows are parsed, which avoids keeping rejected rows in memory but doesn't avoid reading them.
Partitioned directories
If a dataset is laid out in Hive-style directories such as events/year=2025/month=11/part-0.parquet, the directory names act as column values. A filter on year or month can then skip entire files without opening them.
import polars as pl
lf = pl.scan_parquet("events/**/*.parquet", hive_partitioning=True)
recent = lf.filter((pl.col("year") == 2025) & (pl.col("month") == 11))Filters on partition columns are the cheapest possible pushdown, because they remove whole files from the plan.
The optimizer's pipeline
The diagram shows where pushdown fits between your query and execution.
Checking pushdown with explain
You should confirm pushdown instead of assuming it. The script below builds a small dataset so it runs on its own, then prints both the unoptimized and the optimized plan.
import tempfile
from pathlib import Path
import polars as pl
tmp = Path(tempfile.mkdtemp())
for i in range(3):
pl.DataFrame(
{
"user_id": [i * 10 + j for j in range(5)],
"status": ["ok", "error", "ok", "ok", "error"],
"amount": [10.0, 20.0, 30.0, 40.0, 50.0],
"note": ["a", "b", "c", "d", "e"],
}
).write_parquet(tmp / f"part-{i}.parquet")
lf = (
pl.scan_parquet(str(tmp / "*.parquet"))
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print("--- as written ---")
print(lf.explain(optimized=False))
print("--- optimized ---")
print(lf.explain())In the unoptimized plan, the scan sits at the bottom and the filter and select appear above it as separate steps. In the optimized plan, the filter and the column list move into the scan node. You should see something like PROJECT 3/4 COLUMNS (the scan reads user_id, amount and status, but not note) and a SELECTION entry containing the status comparison. The exact wording of the plan differs between Polars versions, so look for the presence of those two pieces, not for exact text.
A common mistake is reading the plan from the top and expecting FILTER to be the first thing you see. The plan reads bottom-up: data flows from the scan upward. If a FILTER node still appears above the scan, the predicate was not pushed down.
When pushdown does not happen
The optimizer only moves a filter or a column selection when doing so cannot change the result. Several patterns block it.
- Filtering on a derived column. A filter on
amount_centscannot move below thewith_columnsthat creates it. Polars may still push down parts of a predicate that reference only source columns, so filter on source columns where possible. - Order-dependent operations.
shift,cum_sum,rank,headand window expressions withoverdepend on which rows are present. Filtering before them would change their values, so a filter placed after them stays after them. - Filtering after aggregation. A filter on an aggregated value such as
total_amount > 1000must run after thegroup_by. It cannot reduce the input to the aggregation. - Opaque Python code.
map_elementsand similar user-defined functions hide which columns they read, so Polars is conservative around them. Prefer native expressions.
The fix is usually to rewrite the query so the filter appears before the blocking operation, when that's logically valid for your problem.
import polars as pl
# Filter on a source column: can be pushed into the scan.
good = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("amount") > 0)
.with_columns((pl.col("amount") * 100).cast(pl.Int64).alias("amount_cents"))
)
# Filter on the derived column: the predicate depends on with_columns output.
awkward = (
pl.scan_parquet("events/*.parquet")
.with_columns((pl.col("amount") * 100).cast(pl.Int64).alias("amount_cents"))
.filter(pl.col("amount_cents") > 0)
)Both queries give the same rows. In the second one, check with explain() whether the filter reached the scan. Polars can sometimes rewrite simple cases, but you should verify instead of relying on it.
Common errors
- Using eager reads, then expecting pushdown.
pl.read_parquet(...).filter(...)loads everything before the filter runs. Pushdown needsscan_*and aLazyFrame. - Calling
.collect()too early. Collecting in the middle of a pipeline and continuing eagerly ends optimization at that point. Keep the whole query lazy and collect once at the end. - Selecting columns late. Pushdown moves a
selectdown for you, but wide intermediate steps can still carry unneeded columns when a barrier blocks pushdown. Select the columns you need near the scan. - Assuming CSV gets the same savings as Parquet. For CSV, pushdown reduces parsing and memory, not file I/O.
- Trusting the plan from a different version. Plan text and optimizer coverage change between Polars releases. Re-check
explain()after upgrading.
Summary of what to check
| Question | Where to look in `explain()` | Typical fix |
|---|---|---|
| Are only needed columns read? | The scan node's column count, such as `PROJECT 3/4 COLUMNS` | Remove unused columns, avoid `select("*")` patterns |
| Is the filter applied at the scan? | A `SELECTION` entry on the scan node | Filter on source columns, before order-dependent steps |
| Is a separate `FILTER` node left above the scan? | A `FILTER` node above other nodes | Move the filter earlier or rewrite the predicate |
| Can whole files be skipped? | Not shown in the plan; depends on layout | Use Hive partitions and filter on the partition columns |
Exercise
A Parquet dataset has columns user_id, status, amount and note. Your query is pl.scan_parquet("events/*.parquet").filter(pl.col("status") == "ok").select("user_id", "amount"). Which columns does the optimized scan read, and why is status among them even though the final result does not contain it?
Show answer
The scan reads user_id, amount and status. Projection pushdown keeps every column used anywhere in the query, and status is needed to evaluate the filter. Only note is skipped.
Exercise
You write pl.scan_parquet("events/*.parquet").with_columns(pl.col("amount").cum_sum().alias("running")).filter(pl.col("status") == "ok"). Can Polars safely push the status filter below the cum_sum? Explain.
Show answer
No. cum_sum depends on every row that comes before it. If rows were filtered out first, the running totals would change and the result would differ from the query as written. The filter stays above the with_columns. If you want running totals over only the "ok" rows, put the filter before the cum_sum in the query, which changes the meaning on purpose and lets the filter be pushed into the scan.
Exercise
A team stores a year of events in one large Parquet file with rows in random date order, and their queries always filter on a date range. Suggest two changes to the layout that would make predicate pushdown skip more data.
Show answer
Sort the data by date before writing, so each row group covers a narrow date range and its min/max statistics let the scan skip row groups outside the filter. Alternatively, split the data into Hive-style partitions such as year=.../month=... and filter on those columns, so whole files are skipped without being opened.