Predicate Pushdown and Execution Plans in PySpark

Spark tutorial · PySpark.in

Predicate pushdown lets Spark apply a filter as early as it safely can: below a join, or inside the data source reader, so less data is read, shuffled and joined. This tutorial shows how to verify it in PySpark with explain(), using examples you can run on this page.

You will learn the difference between filter movement in the logical plan and data-source pushdown, how to read the four stages of explain(True), what PushedFilters, PartitionFilters and ReadSchema really prove, and the cases where Spark must not move a filter.

Run the examples: Every code block below is self-contained: it creates its own small DataFrames, so you can press Run on any block in any order. Exact plan text varies with the Spark version; the operators to look for are named in the text.

1. Does Spark run your code in the order you write it?

Suppose a pipeline joins two DataFrames, then filters rows, then aggregates revenue. Reading the Python from top to bottom, it looks as if Spark must finish the whole join before it filters. It does not have to.

DataFrame transformations are lazy: they only build a logical plan. An action such as show(), count() or write triggers execution, and before that the Catalyst optimizer rewrites the plan with rules that never change the result. One of those rules moves filters as close to the data as possible.

The key idea: If a filter uses only columns from one side of an inner join, Catalyst can move it below the join, so fewer rows enter the join. Whether the filter also reaches the file reader depends on the source, the file format and the expression. Plan inspection is how you check both.

Core terms

2. A reproducible example: filter after the join

Order status belongs to the orders table and state belongs to the customers table. Query A writes the filter after the join. Run it and look at the Optimized Logical Plan section of the output.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("PredicatePushdownDemo").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 101, 120.0, "Delivered"), (2, 101, 80.0, "Cancelled"),

(3, 102, 200.0, "Delivered"), (4, 103, 50.0, "Pending"),

(5, 104, 300.0, "Delivered")],

["order_id", "customer_id", "amount", "order_status"],

)

customers = spark.createDataFrame(

[(101, "Delhi"), (102, "Pune"), (103, "Jaipur"), (104, "Delhi")],

["customer_id", "state"],

)

 

orders.show()

customers.show()

 

# Query A: the filter is written AFTER the join

query_after_join = (

orders

.join(F.broadcast(customers), on="customer_id", how="inner")

.filter(F.col("order_status") == "Delivered")

.groupBy("state")

.agg(F.sum("amount").alias("total_revenue"))

)

 

query_after_join.explain(True)

query_after_join.orderBy("state").show()

```

In the Optimized Logical Plan, the Filter on order_status sits under the join, on the orders branch, even though the code wrote it after the join. Catalyst also adds isnotnull(customer_id) filters on both sides, because an inner join can never match a null key.

3. Same query, filter written first

Query B writes the filter before the join and selects only the columns it needs. For an inner join the two queries are equivalent, so their optimized plans should look the same and their results must match.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("PredicatePushdownDemo").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 101, 120.0, "Delivered"), (2, 101, 80.0, "Cancelled"),

(3, 102, 200.0, "Delivered"), (4, 103, 50.0, "Pending"),

(5, 104, 300.0, "Delivered")],

["order_id", "customer_id", "amount", "order_status"],

)

customers = spark.createDataFrame(

[(101, "Delhi"), (102, "Pune"), (103, "Jaipur"), (104, "Delhi")],

["customer_id", "state"],

)

 

# Query A: filter after the join

query_after_join = (

orders.join(F.broadcast(customers), on="customer_id", how="inner")

.filter(F.col("order_status") == "Delivered")

.groupBy("state").agg(F.sum("amount").alias("total_revenue"))

)

 

# Query B: filter before the join, only the needed columns

delivered = orders.filter(F.col("order_status") == "Delivered").select("customer_id", "amount")

query_before_join = (

delivered.join(F.broadcast(customers.select("customer_id", "state")), on="customer_id", how="inner")

.groupBy("state").agg(F.sum("amount").alias("total_revenue"))

)

 

query_before_join.explain(True)

 

a = sorted(query_after_join.collect())

b = sorted(query_before_join.collect())

print("Same result:", a == b)

for row in b:

print(row["state"], row["total_revenue"])

```

What this example does not show: These DataFrames live in memory, so there is no file scan and no PushedFilters. Section 7 reads real Parquet files to show data-source pushdown.

Writing the filter early is still good style: it makes the intent obvious to the next reader. But do not rely on code order for performance; Catalyst decides, and the plan shows what it decided.

4. Reading explain(True): the four plan stages

explain(True) (the same as explain(mode="extended")) prints four plans. Each answers a different question.

Plan stageWhat it isQuestion it answers
Parsed Logical PlanThe query as Spark parsed it, before names and types are resolved.What structure did Spark read from my code?
Analyzed Logical PlanColumns, tables and data types resolved against the schema. Unresolved or ambiguous column errors appear here.Are all columns and types resolved?
Optimized Logical PlanThe plan after Catalyst rules: filters moved down, columns pruned, constants folded.Which rewrites did Catalyst apply? Is my filter below the join?
Physical PlanThe operators Spark will run: scans, BroadcastHashJoin or SortMergeJoin, Exchange (shuffle), HashAggregate.How will it execute, and where does data move?

Use the optimized logical plan to study filter movement, then the physical plan and the Spark UI to see what actually ran. With Adaptive Query Execution (AQE) on, the physical plan is marked AdaptiveSparkPlan isFinalPlan=false before the query runs; the final plan can change at runtime.

5. What the physical plan markers prove (and what they do not)

MarkerMeaningWhat it does NOT prove
FilterA Spark filter operator in the plan.That the reader skipped any data on disk.
PushedFiltersFilters Spark passed to the data source reader.That every file or row group was skipped; check scan metrics.
PartitionFiltersConditions on partition columns, used to skip whole directories.Anything about filters on ordinary columns.
DataFiltersFilters on data columns attached to the scan.That the source applied them; display varies by source.
ReadSchemaThe columns the scan reads; shows column pruning.The full schema of the dataset.
ExchangeData redistribution across partitions (a shuffle).That something is wrong; ask which operation needs it.

Plan-reading checklist

A filter can move below a join without ever appearing in PushedFilters, and a filter can be pushed to the reader in a query with no join at all. Always say which of the two optimizations you mean.

6. Why filtering early helps performance

AreaBenefit when fewer rows flowCaution
Broadcast joinA smaller build side means a smaller broadcast and in-memory hash table.Broadcast still uses driver and executor memory; it can still run out of memory.
Sort-merge joinFewer rows to shuffle and sort before the merge.A shuffle is still required; partition sizes and skew still matter.
AggregationFewer rows reach the partial and final aggregation.groupBy still shuffles by the grouping key.
Column pruningReading fewer columns reduces I/O and memory, especially with Parquet.Check ReadSchema and what the source supports.

Be careful with claims such as "pushdown cuts network traffic by 90%". Savings depend on how selective the filter is, row width, file format, join strategy, partitioning and cluster resources. Measure your own workload in the Spark UI.

7. Data-source pushdown with Parquet: PushedFilters and PartitionFilters

This example writes the orders to Parquet, partitioned by order_status, and reads them back with two filters: one on the partition column and one on an ordinary column. Look at the FileScan parquet line of the physical plan.

```python

import tempfile

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("ParquetPushdownDemo").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 101, 120.0, "Delivered"), (2, 101, 80.0, "Cancelled"),

(3, 102, 200.0, "Delivered"), (4, 103, 50.0, "Pending"),

(5, 104, 300.0, "Delivered")],

["order_id", "customer_id", "amount", "order_status"],

)

 

path = tempfile.mkdtemp() + "/orders_parquet"

orders.write.mode("overwrite").partitionBy("order_status").parquet(path)

 

result = (

spark.read.parquet(path)

.filter(F.col("order_status") == "Delivered") # partition column

.filter(F.col("amount") > 100) # data column

.select("order_id", "amount")

)

 

result.explain()

result.orderBy("order_id").show()

```

Why the storage format matters

Format or layoutWhat can happenHow to read it
CSV / JSONSupported filters can be checked while rows are parsed, but there are no row-group statistics to skip ranges.PushedFilters does not mean the file was avoided; check bytes read.
Parquet / ORCColumnar storage plus row-group statistics let the reader skip blocks and columns.Skipping works best when data is sorted or clustered on the filter column.
Delta LakeFile-level statistics in the transaction log allow data skipping across files.Data skipping is not the same as partition pruning; it depends on stats and layout.
Partitioned tablesFilters on partition columns remove whole directories.Look for PartitionFilters and filter on the partition column itself.

8. Cases where Spark cannot or must not move a filter

Catalyst only applies rewrites that keep the result identical. These are not "optimizer bugs"; they are cases where moving the filter would change the answer or where Spark cannot see inside the expression.

8.1 A condition that needs columns from both sides

amount - discount > 100 needs amount from orders and discount from coupons, so it can only be checked after rows are matched. The independent condition amount > 50 can still move down.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("BothSidesFilter").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 120.0), (2, 80.0), (3, 200.0), (4, 50.0)], ["order_id", "amount"])

coupons = spark.createDataFrame(

[(1, 10.0), (2, 5.0), (3, 120.0), (4, 0.0)], ["order_id", "discount"])

 

result = (

orders.join(coupons, on="order_id", how="inner")

.filter(F.col("amount") > 50) # one side: can move down

.filter((F.col("amount") - F.col("discount")) > 100) # both sides: stays above the join

)

 

result.explain(True)

result.show()

```

In the optimized plan, amount > 50 moves down to the orders branch. The subtraction condition cannot: Catalyst makes it part of the join condition itself, Join Inner, ((amount - discount) > 100.0) AND (order_id = order_id), because it can only be checked once an order is matched with its coupon.

8.2 Python UDF filters

Catalyst cannot look inside a Python UDF, so it cannot turn it into a source-level filter such as EqualTo(order_status,Delivered). The plan gets a BatchEvalPython (or ArrowEvalPython) step that sends rows to Python. A native expression does the same work inside the JVM and stays fully optimizable.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("PredicatePushdownDemo").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 101, 120.0, "Delivered"), (2, 101, 80.0, "Cancelled"),

(3, 102, 200.0, "Delivered"), (4, 103, 50.0, "Pending"),

(5, 104, 300.0, "Delivered")],

["order_id", "customer_id", "amount", "order_status"],

)

customers = spark.createDataFrame(

[(101, "Delhi"), (102, "Pune"), (103, "Jaipur"), (104, "Delhi")],

["customer_id", "state"],

)

 

from pyspark.sql.functions import udf

from pyspark.sql.types import BooleanType

 

@udf(returnType=BooleanType())

def is_delivered(status):

return status == "Delivered"

 

with_udf = orders.join(customers, on="customer_id").filter(is_delivered(F.col("order_status")))

native = orders.join(customers, on="customer_id").filter(F.col("order_status") == "Delivered")

 

print("=== Python UDF filter ===")

with_udf.explain()

print("=== Native filter ===")

native.explain()

 

print("Same rows:", sorted(with_udf.collect()) == sorted(native.collect()))

```

Compare the two plans. Spark still places the UDF filter on the orders branch below the join, but only after a BatchEvalPython step has sent every row to a Python worker; it cannot push the UDF into a reader or reason about its logic. The native version is a plain Filter that stays in the JVM and can be pushed to Parquet. Prefer built-in functions whenever they express the same logic.

8.3 Outer joins and null semantics

In a left outer join, customers without a matching order still appear, with NULL order columns. Filtering the right side after the join removes those rows; filtering it before the join keeps them. The results differ.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("OuterJoinFilter").getOrCreate()

 

customers = spark.createDataFrame(

[(101, "Delhi"), (102, "Pune"), (103, "Jaipur"), (105, "Mumbai")], ["customer_id", "state"])

orders = spark.createDataFrame(

[(1, 101, "Delivered"), (2, 102, "Cancelled"), (3, 103, "Delivered")],

["order_id", "customer_id", "order_status"])

 

# Filter AFTER the left join: customers without a Delivered order disappear

after = (customers.join(orders, on="customer_id", how="left")

.filter(F.col("order_status") == "Delivered"))

 

# Filter the right side BEFORE the join: every customer stays

before = customers.join(orders.filter(F.col("order_status") == "Delivered"),

on="customer_id", how="left")

 

print("Filter after join:", after.count(), "rows")

after.orderBy("customer_id").show()

print("Filter before join:", before.count(), "rows")

before.orderBy("customer_id").show()

 

after.explain(True)

```

The filter after the join rejects NULL, so the left join behaves like an inner join. Catalyst notices this and rewrites it: the optimized plan of after shows Join Inner. That is a legal rewrite because the result is unchanged; moving the filter blindly would not be.

8.4 Non-deterministic expressions

Expressions such as rand() can return a different value each time they are evaluated, so moving them to another point in the plan could change the result. Spark is conservative with them.

8.5 The RDD API

RDD transformations are lazy too, but RDDs do not go through Catalyst. They get no filter movement, no column pruning and no data-source pushdown, which is one reason the DataFrame API is usually faster.

9. Inspect the plan in formatted mode

explain("formatted") splits the physical plan into a short outline and numbered details per operator, which is easier to read for larger queries.

```python

from pyspark.sql import SparkSession, functions as F

 

spark = SparkSession.builder.appName("PredicatePushdownDemo").getOrCreate()

 

orders = spark.createDataFrame(

[(1, 101, 120.0, "Delivered"), (2, 101, 80.0, "Cancelled"),

(3, 102, 200.0, "Delivered"), (4, 103, 50.0, "Pending"),

(5, 104, 300.0, "Delivered")],

["order_id", "customer_id", "amount", "order_status"],

)

customers = spark.createDataFrame(

[(101, "Delhi"), (102, "Pune"), (103, "Jaipur"), (104, "Delhi")],

["customer_id", "state"],

)

 

query = (

orders.join(F.broadcast(customers), on="customer_id")

.filter(F.col("order_status") == "Delivered")

.groupBy("state").agg(F.sum("amount").alias("total_revenue"))

)

 

query.explain("formatted")

```

10. A practical verification workflow

  1. Build the baseline query and save its plan with explain(True).
  2. Identify the filters, join type, join keys, aggregation and any Exchange nodes.
  3. Read the Optimized Logical Plan: is each eligible filter below the join?
  4. Read the Physical Plan: join strategy, scan nodes, PushedFilters, PartitionFilters and ReadSchema.
  5. For file-based sources, test on representative Parquet or Delta data, not only on in-memory samples.
  6. Run the alternatives on the same data and compare input size, shuffle read and write, spill, task skew and duration in the Spark UI.
  7. Repeat runs when caching, autoscaling or AQE could affect the numbers, and record the Spark version and settings.

Best practices

11. Interview questions

Q1. What is predicate pushdown in Spark?

An optimization that applies a filter as close to the data as is semantically safe: lower in the plan (for example below a join) and, when the source supports it, inside the reader, so less data is processed.

Q2. How is filter movement below a join different from data-source pushdown?

Filter movement changes where the Filter sits in the logical plan. Data-source pushdown passes a supported condition to the reader (PushedFilters). Either can happen without the other.

Q3. How do you verify that a filter moved below a join?

Run explain(True) and check that the Filter appears on the correct branch under the Join in the Optimized Logical Plan.

Q4. What does PushedFilters prove?

That Spark passed those filters to the source. It does not prove how much data was skipped; check the file format and the scan metrics in the Spark UI.

Q5. What is the difference between PartitionFilters and PushedFilters?

PartitionFilters use partition columns to skip whole directories. PushedFilters are conditions on data columns handed to the reader, for example for Parquet row-group skipping.

Q6. Does a Python UDF stop all optimization?

No. Spark cannot push or reorder the UDF expression itself, but other independent parts of the plan are still optimized. Prefer native functions for filters.

Q7. Why can a filter after a left join change the join type?

A filter that rejects NULLs on the right side removes the unmatched rows, so the left join returns the same rows as an inner join. Catalyst rewrites it to an inner join because the result is identical.

Q8. Are RDD transformations eager?

No, they are lazy too. RDDs differ because they bypass the Catalyst optimizer, so they get no pushdown or column pruning.

Next: practise reading plans on real data in the PySpark online compiler, or try timed problems in the Challenge Arena.

More Spark tutorials

PySpark tutorial: all lessons · All tutorials · Try the free PySpark compiler · Practice challenges