The Spark Catalyst optimizer turns your SQL or DataFrame code into a faster execution plan before Spark runs it. It rewrites the query with rules such as predicate pushdown, column pruning and constant folding, picks join strategies, and compiles stages into Java code. Since Spark 3.2, Adaptive Query Execution keeps improving that plan while the query runs.
Below: the 4 phases, what each optimization buys you, how Catalyst and AQE split the work, and how to read the plan Catalyst produced. The deep dive into Catalyst's internals is at the end.
What the Catalyst optimizer is
Catalyst is the query optimizer inside Spark SQL. Every SQL query, DataFrame, Dataset and PySpark DataFrame call goes through it. You write what you want. Catalyst decides how Spark gets it.
That's why two very different-looking pieces of code often run the same way. Catalyst rewrites both into the same plan.
It doesn't touch RDD code. If you drop down to RDDs, you give up these optimizations.
The 4 phases of the Catalyst pipeline
| Phase | What happens | Example |
|---|---|---|
| Analysis | Resolves table and column names, checks types, consults the cache | index becomes index#28, a resolved column |
| Logical optimization | Rewrites the plan with rules, without changing the result | Two filters merged into one and moved before the select |
| Physical planning | Turns the logical plan into Spark operators and picks algorithms | A join becomes a broadcast hash join or a sort merge join |
| Code generation | Compiles chains of operators into one Java function | *(1) markers in the plan show a whole-stage codegen stage |

The input is a SQL query or a DataFrame action. The output is a physical plan that becomes the RDD graph Spark schedules.
What Catalyst does for performance
Most of the speedup comes from a handful of rules:
- Predicate pushdown: moves filters as close to the data source as possible. Parquet, ORC and Delta can skip files and row groups, so Spark reads less.
- Column pruning: reads only the columns the query uses. On wide tables this cuts I/O sharply.
- Constant folding: computes fixed expressions once at planning time, so
1 + 2never runs per row. - Filter combining and simplification: merges adjacent filters and rewrites predicates, for example a one-item
INlist into an equality check. - Join selection: picks the join algorithm. Broadcast hash join comes first when one side is small enough to fit in memory, which avoids a shuffle of the large side.
- Whole-stage code generation: fuses operators into one Java function, so rows aren't passed between operators one call at a time.
Catalyst can't fix everything. It works from estimates. If those estimates are wrong, or the data is skewed, it can still pick a slow plan. That's where AQE comes in.
Catalyst vs Adaptive Query Execution (AQE)
Catalyst plans the query before it runs. AQE re-plans between stages while it runs, using real statistics from the stages that already finished.
| Catalyst | AQE | |
|---|---|---|
| When it runs | Before execution | During execution, at shuffle boundaries |
| What it uses | Rules, plus estimated sizes and table statistics | Actual sizes of completed shuffle stages |
| What it changes | The whole logical and physical plan | Join strategy, number of shuffle partitions, skewed partitions |
| On by default | Always | Since Spark 3.2 (spark.sql.adaptive.enabled) |
What AQE adds on top of Catalyst:
- Coalesces small post-shuffle partitions into fewer, larger ones
- Switches a sort merge join to a broadcast join when one side turns out to be small
- Splits skewed partitions in joins
- On Databricks, also drops branches that turn out to be empty
AQE only kicks in for queries with at least one shuffle (a join or aggregation, for example) or a subquery. A simple scan and filter, like the example below, never uses it.
For skew in detail, see Part 2: Data Skew & Garbage Collection. For join choices on Databricks, see Optimizing Databricks Slow Joins.
[cta-banner]
How to see what Catalyst did to your query
Call explain() on any DataFrame, or run EXPLAIN before a SQL query. Since Spark 3.0 you can pick a mode:
| Mode | Shows |
|---|---|
simple (default) | Physical plan only |
extended | Parsed, analyzed, optimized logical plans and the physical plan |
formatted | Physical plan as a numbered outline with details per operator |
cost | Optimized logical plan with size and row estimates |
codegen | The generated Java code |
df.explain(mode="extended")
Read plans from the bottom up. The bottom node reads the data. The top node is the result.
Here's an (intentionally inefficient) query we'll follow through the pipeline:
val result = session.read.option("header", "true").csv(outputLoc) .select("letter", "index") .filter($"index" < 10) .filter(!$"letter".isin("h") && $"index" > 6) result.show()
The full program is on GitHub. Plan output below is from the original Spark 2.4 run. Newer versions format it slightly differently, but the shape is the same.
After analysis, the plan still mirrors the code: read, select, then two filters.
Filter (NOT letter#26 IN (h) && (cast(index#28 as int) > 6)) +- Filter (cast(index#28 as int) < 10) +- Project [letter#26, index#28] +- Relation[letter#26,letterUppercase#27,index#28] csv
After logical optimization, the two filters are merged, pushed below the select, and the IN is rewritten as an equality check:
Project [letter#26, index#28] +- Filter ((((isnotnull(index#28) && isnotnull(letter#26)) && (cast(index#28 as int) < 10)) && NOT (letter#26 = h)) && (cast(index#28 as int) > 6)) +- Relation[letter#26,letterUppercase#27,index#28] csv
The final physical plan pushes three predicates into the file scan and runs everything in one generated function, marked *(1):
*(1) Project [letter#26, index#28] +- *(1) Filter ((((isnotnull(index#28) && isnotnull(letter#26)) && (cast(index#28 as int) < 10)) && NOT (letter#26 = h)) && (cast(index#28 as int) > 6)) +- *(1) FileScan csv [letter#26,index#28] PushedFilters: [IsNotNull(index), IsNotNull(letter), Not(EqualTo(letter,h))]
What to look for in your own plans:
PushedFilterson the scan. Empty means every row gets read.ReadSchemalisting only the columns you need.BroadcastHashJoinvsSortMergeJoin, and whether that matches the table sizes.Exchangenodes. Each one is a shuffle.AdaptiveSparkPlan isFinalPlan=trueafter the run, which means AQE was active.
Cost-based optimization and its limits
Catalyst is mostly rule-based. Its cost-based optimizer (CBO) uses table and column statistics to improve size estimates and join order.
- Open-source Spark: off by default. Set
spark.sql.cbo.enabledto true. Join reordering needsspark.sql.cbo.joinReorder.enabledtoo. - Databricks: on by default.
- Either way, it needs statistics. Collect them with
ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNS. Missing or stale statistics can lead to a bad join order or join type.
The CBO's scope is narrow. In the Spark source, it computes cost from cardinality and size because physical operator costs aren't available. It doesn't explore a space of physical plans and pick the cheapest. The planner takes the first valid physical plan its strategies return.
Its main effects are on joins: the CostBasedJoinReorder and ReorderJoin rules, and better size estimates for the JoinSelection strategy. Of the column statistics, mainly distinct counts and null counts feed those decisions.
In our example the CBO does nothing. It's off by default, the input is raw CSV with no statistics, and there's no join.
[cta-banner]
Inside Catalyst (deep dive)
This section is for engineers who want to see how Catalyst is built. Line references point to the Spark 2.4 and 3.0 source, where the original analysis was done.
Trees and nodes
Every Catalyst plan is a Scala tree that descends from TreeNode. A node has zero or more children, which are also tree nodes. Two key subclasses mirror database plans: LogicalPlan for algebraic operators like Join, and SparkPlan for physical operators like SortMergeJoinExec.
Transformations
Rules are pattern matches applied to trees. This snippet rewrites the expression -((11 - 2) * (9 - 5)) into -((1 + 0) + (1 + 5)):
import org.apache.spark.sql.catalyst.expressions._ val firstExpr: Expression = UnaryMinus(Multiply(Subtract(Literal(11), Literal(2)), Subtract(Literal(9), Literal(5)))) val transformed: Expression = firstExpr transformDown { case BinaryOperator(l, r) => Add(l, r) case IntegerLiteral(i) if i > 5 => Literal(1) case IntegerLiteral(i) if i < 5 => Literal(0) }
transformDown takes a partial function, so a rule only has to match the nodes it cares about. UnaryMinus and the literal 5 match no case and stay as they are. The same technique scales up to rules like cost-based join reordering, which runs a dynamic programming algorithm.
Logical rules
Rules run in groups called batches. Some batches run once. Others repeat until the plan stops changing or hits an iteration limit. In Spark 2.4.7 the optimizer had 25 batches and 109 rules (69 distinct). Counts change with each release. Our CollectBatches program prints them for your version.
In the example query, 12 rules fire, including:
PushDownPredicate(twice), moving both filters below the selectCombineFilters, merging the two filtersOptimizeIn, replacing a one-itemINwith an equality checkRewritePredicateSubquery, reordering the merged predicate
Statistics
The Statistics class holds estimates per plan node: size in bytes, row count, and column-level values (distinct count, nulls, min and max, average and max length, histogram). With the CBO off, Catalyst uses size only. With it on, it also estimates column statistics for aggregates, filters, joins and projects.
Physical planning and preparation
The SparkPlanner applies strategies that map logical nodes to physical ones: filter pushdown into the data source, partition and bucket scans, the aggregation algorithm, and the join algorithm. JoinSelection checks broadcast hash join first and returns as soon as its conditions are met.
Preparation rules then finish the plan. EnsureRequirements adds shuffles where needed, ReuseExchange removes duplicate ones, and CollapseCodegenStages fuses operators into whole-stage codegen functions, compiled at runtime by Janino.
How AQE plugs in
AQE wraps the physical plan in an AdaptiveSparkPlanExec root node. It splits the plan into query stages at shuffle boundaries and runs them bottom up. After each stage, it uses the real output sizes to re-plan the stages above, keeping a new plan only if it has fewer shuffles.
Extending Catalyst
You can add your own logical rules and strategies, or exclude built-in rules with spark.sql.optimizer.excludedRules. Few teams do. The work is hard to maintain, and machine types, data layout and skew often matter more than the plan.
How Unravel fits in
Catalyst optimizes one query at a time, from estimates. It can't see that the same inefficient join runs every day across many teams' jobs. Arvix, Unravel's autonomous AI operator, rewrites inefficient queries across your entire fleet and resizes compute based on actual workload demand. Learn more about Spark optimization with Unravel.
Get a free health check to see where your Spark workloads lose time and money.





