Sub topic 11
Projection pushdown: read only the columns you use
This chapter assumes you know Polars expressions (pl.col, select, filter, with_columns, group_by) and have read a CSV or Parquet file before. It also assumes you have seen explain() output. You should know that a LazyFrame records a plan and that collect() runs it.
What projection pushdown does
A projection is the set of columns a query needs. Projection pushdown moves that set as close to the data source as possible. The optimiser works out which columns the whole query uses and tells the scan to load only those.
Wide tables benefit most. A file with 80 columns where the query touches 3 only needs to load those 3. This cuts I/O, memory use and the work of parsing or decoding values.
Dropping unused columns early does not change the result. The optimiser only removes columns that no later step reads.
How it differs by file format
How much you save depends on how the format stores data.
| Source | What pushdown saves |
|---|---|
| Parquet | Stores data column by column. Unused column chunks are never read from disk. |
| CSV | Stores data row by row. Every line must still be read, but unused fields are not parsed or kept in memory. |
| In-memory `LazyFrame` | Nothing is read from disk. The optimiser drops unused columns from later steps so they are not carried through the query. |
Parquet gives the largest gain, because skipping a column means skipping its bytes. With CSV, the file still has to be scanned from start to end.
A worked example
This query reads a Parquet file but uses only three columns.
import polars as pl
lf = (
pl.scan_parquet("events.parquet")
.select("user_id", "ts", "country")
.filter(pl.col("country") == "NO")
.head(5)
)
print(lf.explain())
print(lf.collect())The file may hold many more columns, such as device, referrer or payload. None of them appear in the query, so none are needed.
In the optimised plan, the scan node reports the columns it will load. The exact wording depends on your Polars version, but you should see a line like this:
Parquet SCAN [events.parquet]
PROJECT 3/12 COLUMNS
SELECTION: [(col("country")) == ("NO")]PROJECT 3/12 COLUMNS means 3 of the file's 12 columns are loaded. Compare it with the unoptimised plan, which shows PROJECT */12 COLUMNS. The * means all columns. The SELECTION line is predicate pushdown acting on the same scan, which the previous chapter covered.
Columns used only by a filter
A column does not have to appear in the final output to be needed. If a filter or a join key uses it, the scan must still load it.
import polars as pl
lf = (
pl.scan_parquet("events.parquet")
.filter(pl.col("country") == "NO")
.select("user_id")
)
print(lf.explain())The result has only user_id. The scan loads two columns, user_id and country. The optimiser works backwards from the final output. It collects every column used by any step, whether the step is a filter, a sort key, a group key, a join key or an aggregation input.
A pushdown you can see with no files
You can check the effect without any file by using a LazyFrame built from a dictionary. The plan then shows a DF node with a projection.
import polars as pl
lf = pl.LazyFrame(
{
"a": [1, 2, 3],
"b": [4, 5, 6],
"c": [7, 8, 9],
"d": [10, 11, 12],
}
)
query = lf.with_columns(total=pl.col("a") + pl.col("b")).select("total")
print(query.explain(optimized=False))
print(query.explain())The unoptimised plan keeps all four source columns through with_columns and then selects total. The optimised plan reads only a and b. Columns c and d are never used, so they are dropped at the source.
Reading the plan for projection
Look for these signs when you check a plan.
PROJECT n/m COLUMNSon a scan node shows how many columns the scan loads. A smallernis better.PROJECT */m COLUMNSmeans every column is loaded. Check whether the query really needs them all.- A
SELECTnode above the scan means a projection that was not pushed into it. The scan may still load more than needed.
Do not rely on a single phrase. The text format of explain() changes between versions, so confirm in your own version what an all-columns scan looks like.
When projection pushdown cannot help
Projection pushdown works because the optimiser can see which columns every expression reads. It loses that knowledge in some cases.
- Selecting everything.
pl.all(),pl.col("*")or a regex that matches all columns means every column is used. - Python UDFs that receive a whole row or frame.
map_rowsandpipewith a function that takes aDataFrameare opaque. The optimiser cannot know which columns the function reads, so it keeps them all. This is covered in the chapter on optimisation barriers. - Collecting early. Calling
collect()and then.lazy()again ends the plan. The first query has no knowledge of what the second one needs.
A common mistake is to write select late and expect it to help the scan. In a pure lazy query it does help, because the optimiser moves it. If anything in between blocks the optimiser, the scan loads everything.
import polars as pl
lf = pl.scan_parquet("events.parquet")
# Opaque: the function sees whole frames, so all columns are kept.
blocked = lf.map_batches(lambda df: df).select("user_id")
# Transparent: the scan can load only user_id.
clear = lf.select("user_id")
print(blocked.explain())
print(clear.explain())map_batches runs a Python function on the whole frame. Because Polars cannot know which columns that function reads, it loads all of them unless you tell it otherwise. Newer versions of map_batches accept hints such as projection_pushdown=True. Use them only when your function really does not depend on the dropped columns.
Practical advice
- Select the columns you need explicitly. Name them rather than using
pl.all(). - Stay in lazy mode from the scan to the final
collect(). - Prefer native expressions to Python functions, so the optimiser can read them.
- Check
explain()and confirm that the scan loads fewer columns than the file holds. - For repeated analysis of wide CSV files, convert them to Parquet once. Projection pushdown then skips bytes rather than only parsing.
Checking the benefit
To measure the gain, run the same query with and without the optimisation and compare time and memory.
import time
import polars as pl
lf = (
pl.scan_parquet("events.parquet")
.select("user_id", "country")
.group_by("country")
.agg(pl.col("user_id").n_unique())
)
for enabled in (True, False):
start = time.perf_counter()
lf.collect(projection_pushdown=enabled)
elapsed = time.perf_counter() - start
print(f"projection_pushdown={enabled}: {elapsed:.3f}s")Run the loop more than once, because the first read warms the operating system's file cache. Results on a small file will be close. The difference grows with the number of unused columns and the size of the file.
Exercise
A Parquet file has 40 columns. You run pl.scan_parquet("f.parquet").filter(pl.col("status") == "ok").select("id"). How many columns does the optimised scan load, and why?
Show answer
Two columns, id and status. id is needed for the output and status is needed by the filter. The other 38 columns are not used by any step, so projection pushdown leaves them unread.
Exercise
Why does projection pushdown save more time on Parquet than on CSV?
Show answer
Parquet stores each column separately, so unused columns are never read from disk. CSV stores whole rows, so every line must still be read, and pushdown only avoids parsing and keeping the unused fields.