Sub topic 9
Lazy evaluation and query optimization
This chapter assumes you know basic Python, SQL, and the eager versus lazy distinction from the execution models chapter. It explains why lazy engines can run the same query faster than eager ones, and how to check what the optimizer did.
Eager and lazy in one paragraph
An eager tool runs each step as soon as you write it. pandas loads the data, then filters it, then aggregates it. A lazy tool records your steps as a plan and runs nothing until you ask for a result. Polars (collect()), Spark (show(), write, and other actions), and DuckDB (which plans a whole SQL statement before running it) all work this way.
Because the engine sees the whole query before reading data, it can rewrite the plan.
What the optimizer does
Three optimizations account for most of the gain:
| Optimization | What it does | Effect |
|---|---|---|
| Projection pushdown | Reads only the columns the query uses | Less I/O and memory |
| Predicate pushdown | Applies filters at the scan, using Parquet row-group statistics to skip data | Fewer rows read |
| Expression reordering and fusion | Combines steps, removes unused work | Fewer passes over the data |
Columnar formats make the first two possible. Parquet stores each column separately and keeps min/max statistics per row group, so a reader can skip what it does not need.
Inspecting a plan in Polars
Call explain() on a LazyFrame to see the optimized plan without processing any data.
import polars as pl
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.select("region", "revenue")
)
print(lf.explain())In the output, look for the filter appearing inside the scan node and for a projection of only region and revenue. That shows both pushdowns happened. Even if the file has fifty columns, only two are read.
DuckDB offers EXPLAIN for the same purpose, and Spark offers DataFrame.explain().
import duckdb
print(
duckdb.sql(
"EXPLAIN SELECT region, sum(revenue) FROM 'sales.parquet' GROUP BY region"
).fetchall()
)Common errors
- Forcing early execution. Calling
collect()in the middle of a pipeline, or converting to pandas, ends the optimization window. Collect once, at the end. - Using
read_parquetinstead ofscan_parquetin Polars.read_parquetis eager. It loads the data before any filter can be pushed down. - Assuming laziness hides errors. A misspelled column often fails only at
collect()or the action, not on the line that contains the typo. Test with a small sample. - Repeating work. A lazy plan reruns from the source each time you trigger it. In Spark, calling
show()and thencount()on the same uncached DataFrame computes it twice. Cache or write out an intermediate result if you reuse it. - Trusting the plan without reading it. Opaque Python functions (such as
map_elementsin Polars or Python UDFs in Spark) are black boxes to the optimizer and can block pushdown.
Limits
Lazy evaluation does not help when the data is already in memory and the work is a single cheap step. Eager pandas can be simpler to debug because you see each intermediate result. Lazy plans trade that visibility for speed and lower memory use.
Exercise
A teammate writes pl.read_parquet("sales.parquet").filter(pl.col("revenue") > 0).select("region", "revenue") on a 50-column file and finds it uses a lot of memory. What two changes make it lazy and let the optimizer read only the needed data?
Show answer
Replace read_parquet with scan_parquet so the query becomes a LazyFrame, and add .collect() at the end to run it. The optimizer can then push the filter into the scan and read only the region and revenue columns. Running explain() before collect() confirms this.