๐Ÿš€ EXPLAIN, Hints & Caching

Writing a query that returns the right answer is half the job. The other half is knowing how Spark runs it. EXPLAIN shows you Spark's plan for a query, hints let you steer that plan, and caching and statistics help Spark avoid repeated work.

This tutorial is about reading plans and using those tools from SQL. For the theory behind them, see Catalyst Optimizer and Join Strategies.


1. Sample Data

Plans over in-memory views are not very interesting, so this tutorial writes the data to Parquet tables. Start with the employees view from the introduction:

CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)

Then save it as a Parquet table, along with a small departments table:

DROP TABLE IF EXISTS emp_parquet;
CREATE TABLE emp_parquet USING parquet AS SELECT * FROM employees;

DROP TABLE IF EXISTS departments;
CREATE TABLE departments USING parquet AS
SELECT * FROM VALUES
  ('Engineering', 'Floor 3'),
  ('Sales',       'Floor 1'),
  ('Marketing',   'Floor 2'),
  ('HR',          'Floor 1')
AS departments(dept, location)

The DROP TABLE IF EXISTS lines let you re-run the snippet without an "already exists" error. Tables & Views explains managed tables in detail.


2. Running EXPLAIN

Put EXPLAIN in front of any query to see its plan instead of its result. Spark does not run the query:

-- Syntax
EXPLAIN [EXTENDED | FORMATTED | COST] query
ModeWhat you get
EXPLAINThe physical plan: the steps Spark will actually execute
EXPLAIN EXTENDEDFour plans: parsed, analyzed, optimized logical, and physical
EXPLAIN FORMATTEDA short outline of the physical plan, then details for each step
EXPLAIN COSTThe optimized logical plan with size statistics, plus the physical plan

In a Databricks %sql cell, the plan appears as text. In PySpark, spark.sql("EXPLAIN ...") returns a one-row DataFrame, and .show() prints the plan on one line with \n in it. Print the plan text instead:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT name, salary FROM emp_parquet WHERE salary > 60000
""").first()[0])
== Physical Plan ==
*(1) Filter (isnotnull(salary#34) AND (salary#34 > 60000))
+- *(1) ColumnarToRow
   +- FileScan parquet spark_catalog.default.emp_parquet[name#32,salary#34] Batched: true, DataFilters: [isnotnull(salary#34), (salary#34 > 60000)], Format: Parquet, Location: InMemoryFileIndex(1 paths)[...], PartitionFilters: [], PushedFilters: [IsNotNull(salary), GreaterThan(salary,60000)], ReadSchema: struct<name:string,salary:int>

The plans in this tutorial come from a real run on Spark 3.5.5. The long file paths are shortened to [...]. The numbers after # (like salary#34) are internal column ids and will be different on your machine.


3. Reading a Physical Plan

A plan is a tree. Read it from the bottom up: the bottom step runs first and feeds its rows to the step above it.

Step (bottom to top)What it means
FileScan parquet ...emp_parquet[name, salary]Read the Parquet files
ColumnarToRowConvert Parquet's column batches into rows
Filter (... salary > 60000)Keep matching rows

The FileScan line holds two important optimizations:

  • Column pruning. ReadSchema: struct<name:string,salary:int> shows Spark reads only the 2 columns the query uses, not all 7. Parquet stores each column separately, so the other columns are never read from disk. This is one reason to avoid SELECT * on wide tables.
  • Filter pushdown. PushedFilters: [IsNotNull(salary), GreaterThan(salary,60000)] means the filter is handed to the Parquet reader, which can skip chunks of the file whose salary values cannot match.

The *(1) in front of a step means it runs inside whole-stage code generation: Spark fuses those steps into one generated function, which avoids passing rows between separate operators.

Notice also that Spark added isnotnull(salary) on its own. salary > 60000 can never be true for a NULL salary, so the optimizer adds the check to drop those rows early.


4. EXPLAIN EXTENDED: From Query to Plan

EXPLAIN EXTENDED shows each stage the query goes through. These are the first three plans for the same query (the physical plan at the end is the same as above):

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN EXTENDED
SELECT name, salary FROM emp_parquet WHERE salary > 60000
""").first()[0])
== Parsed Logical Plan ==
'Project ['name, 'salary]
+- 'Filter ('salary > 60000)
   +- 'UnresolvedRelation [emp_parquet], [], false

== Analyzed Logical Plan ==
name: string, salary: int
Project [name#32, salary#34]
+- Filter (salary#34 > 60000)
   +- SubqueryAlias spark_catalog.default.emp_parquet
      +- Relation spark_catalog.default.emp_parquet[emp_id#31,name#32,dept#33,salary#34,hire_date#35,manager_id#36,city#37] parquet

== Optimized Logical Plan ==
Project [name#32, salary#34]
+- Filter (isnotnull(salary#34) AND (salary#34 > 60000))
   +- Relation spark_catalog.default.emp_parquet[emp_id#31,name#32,dept#33,salary#34,hire_date#35,manager_id#36,city#37] parquet
PlanWhat Spark did
ParsedTurned your SQL text into a tree. Names are not checked yet ('UnresolvedRelation, the ' marks unresolved names)
AnalyzedLooked up the table and columns in the catalog and attached types
OptimizedApplied rules, such as adding isnotnull(salary)
PhysicalChose how to execute each step (file scan, join algorithm, shuffles)

A typo in a column name fails at the analyzed step, which is why Spark reports it before running anything.


5. EXPLAIN FORMATTED

For bigger queries, the one-line-per-step format gets hard to read. EXPLAIN FORMATTED prints a short numbered outline, then the details of each step:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN FORMATTED
SELECT name, salary FROM emp_parquet WHERE salary > 60000
""").first()[0])
== Physical Plan ==
* Filter (3)
+- * ColumnarToRow (2)
   +- Scan parquet spark_catalog.default.emp_parquet (1)


(1) Scan parquet spark_catalog.default.emp_parquet
Output [2]: [name#32, salary#34]
Batched: true
Location: InMemoryFileIndex [...]
PushedFilters: [IsNotNull(salary), GreaterThan(salary,60000)]
ReadSchema: struct<name:string,salary:int>

(2) ColumnarToRow [codegen id : 1]
Input [2]: [name#32, salary#34]

(3) Filter [codegen id : 1]
Input [2]: [name#32, salary#34]
Condition : (isnotnull(salary#34) AND (salary#34 > 60000))

The numbers in the outline match the numbered sections below it, so you can look up any step quickly.


6. Spotting Shuffles

A shuffle moves rows between machines so that rows with the same key end up together. It is usually the most expensive part of a query. In a plan, a shuffle shows up as Exchange:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT dept, COUNT(*) AS n FROM emp_parquet GROUP BY dept
""").first()[0])
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[dept#33], functions=[count(1)])
   +- Exchange hashpartitioning(dept#33, 4), ENSURE_REQUIREMENTS, [plan_id=132]
      +- HashAggregate(keys=[dept#33], functions=[partial_count(1)])
         +- FileScan parquet spark_catalog.default.emp_parquet[dept#33] Batched: true, DataFilters: [], Format: Parquet, Location: InMemoryFileIndex(1 paths)[...], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<dept:string>

Reading bottom up, a GROUP BY runs in two phases:

  1. partial_count: each task counts the rows it already has, per department.
  2. Exchange hashpartitioning(dept, 4): the partial counts are shuffled so each department lands in one partition. The 4 is the number of shuffle partitions; this run set spark.sql.shuffle.partitions to 4, and the default is 200.
  3. count: the partial counts are added up into the final result.

The partial step means only one small row per department per task crosses the network, not every employee row.

AdaptiveSparkPlan isFinalPlan=false means Adaptive Query Execution (AQE) is on, and it may still change this plan while the query runs, using real sizes it measures along the way. You only see the final plan after the query has run (in the Spark UI). See Adaptive Query Execution.


7. Join Strategies and Join Hints

For a join, the plan shows which join algorithm Spark picked. With a small departments table, Spark picks a broadcast join:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT e.name, d.location
FROM emp_parquet e JOIN departments d ON e.dept = d.dept
""").first()[0])
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [name#32, location#74]
   +- BroadcastHashJoin [dept#33], [dept#73], Inner, BuildRight, false
      :- Filter isnotnull(dept#33)
      :  +- FileScan parquet spark_catalog.default.emp_parquet[name#32,dept#33] ...
      +- BroadcastExchange HashedRelationBroadcastMode(List(input[0, string, false]),false), [plan_id=166]
         +- Filter isnotnull(dept#73)
            +- FileScan parquet spark_catalog.default.departments[dept#73,location#74] ...

BroadcastHashJoin ... BuildRight means Spark copies the right side (departments) to every machine, so the big side never has to be shuffled. Spark does this automatically when a table is smaller than spark.sql.autoBroadcastJoinThreshold (10 MB by default):

SET spark.sql.autoBroadcastJoinThreshold
+------------------------------------+---------+
|key                                 |value    |
+------------------------------------+---------+
|spark.sql.autoBroadcastJoinThreshold|10485760b|
+------------------------------------+---------+

Setting the threshold to -1 turns automatic broadcasting off:

SET spark.sql.autoBroadcastJoinThreshold = -1
+------------------------------------+-----+
|key                                 |value|
+------------------------------------+-----+
|spark.sql.autoBroadcastJoinThreshold|-1   |
+------------------------------------+-----+

Now the same join becomes a sort-merge join: both sides are shuffled by dept (Exchange), sorted, and merged:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT e.name, d.location
FROM emp_parquet e JOIN departments d ON e.dept = d.dept
""").first()[0])
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [name#32, location#74]
   +- SortMergeJoin [dept#33], [dept#73], Inner
      :- Sort [dept#33 ASC NULLS FIRST], false, 0
      :  +- Exchange hashpartitioning(dept#33, 4), ENSURE_REQUIREMENTS, [plan_id=208]
      :     +- Filter isnotnull(dept#33)
      :        +- FileScan parquet spark_catalog.default.emp_parquet[name#32,dept#33] ...
      +- Sort [dept#73 ASC NULLS FIRST], false, 0
         +- Exchange hashpartitioning(dept#73, 4), ENSURE_REQUIREMENTS, [plan_id=209]
            +- Filter isnotnull(dept#73)
               +- FileScan parquet spark_catalog.default.departments[dept#73,location#74] ...

Join hints let you ask for a strategy directly. A hint is a special comment, /*+ ... */, right after SELECT. Even with automatic broadcasting still off, the BROADCAST hint brings the broadcast join back:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT /*+ BROADCAST(d) */ e.name, d.location
FROM emp_parquet e JOIN departments d ON e.dept = d.dept
""").first()[0])
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [name#32, location#74]
   +- BroadcastHashJoin [dept#33], [dept#73], Inner, BuildRight, false
      ...

Put the setting back to its default with RESET:

RESET spark.sql.autoBroadcastJoinThreshold

The main join hints:

HintStrategy in the planUse when
/*+ BROADCAST(t) */BroadcastHashJoint is small enough to fit in memory on every executor
/*+ MERGE(a, b) */SortMergeJoinBoth sides are large (Spark's usual choice for big joins)
/*+ SHUFFLE_HASH(t) */ShuffledHashJoinOne side is medium-sized: too big to broadcast, small enough to hash per partition

Name the table alias in the hint (d), not the original table name, when the query uses aliases.

Common mistake: Broadcasting a table that is too large. The broadcast side is collected on the driver and copied to every executor, so forcing BROADCAST on a multi-gigabyte table can crash the job with out-of-memory errors. Hints are instructions, not suggestions, so check sizes first.


8. Partitioning Hints

Three more hints control how the result is split into partitions, which matters most right before writing files:

HintPlan stepEffect
/*+ REPARTITION(2, dept) */Exchange hashpartitioning(dept, 2)Full shuffle into 2 partitions by dept
/*+ COALESCE(1) */Coalesce 1Merge into 1 partition without a shuffle
/*+ REBALANCE */Exchange RoundRobinPartitioning(...)Even out partition sizes; AQE can split or merge them
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT /*+ COALESCE(1) */ * FROM emp_parquet
""").first()[0])
== Physical Plan ==
Coalesce 1
+- *(1) ColumnarToRow
   +- FileScan parquet spark_catalog.default.emp_parquet[emp_id#31,name#32,dept#33,salary#34,hire_date#35,manager_id#36,city#37] ...

There is no Exchange in this plan, which is why COALESCE is cheaper than REPARTITION. The catch is that it can only reduce the number of partitions, and it can leave them uneven. To learn more, see Repartition and Coalesce.


9. Changing Settings with SET

SET key = value changes a Spark SQL setting for the current session, and SET key shows its current value. The most commonly tuned one is the number of partitions after a shuffle:

SET spark.sql.shuffle.partitions = 8
+----------------------------+-----+
|key                         |value|
+----------------------------+-----+
|spark.sql.shuffle.partitions|8    |
+----------------------------+-----+

The default of 200 is too many for small data (lots of tiny tasks) and too few for very large data (huge tasks). With AQE on, which is the default in Spark 3.5, Spark merges small shuffle partitions at runtime, so the default is a reasonable starting point:

SET spark.sql.adaptive.enabled
+--------------------------+-----+
|key                       |value|
+--------------------------+-----+
|spark.sql.adaptive.enabled|true |
+--------------------------+-----+

RESET key puts one setting back to its default, and plain RESET resets every setting you changed in this session:

RESET spark.sql.shuffle.partitions

10. Caching Tables

If several queries read the same data, caching keeps it in memory (spilling to disk if needed) after the first read:

CACHE TABLE emp_parquet

CACHE TABLE is eager: it reads the whole table right away. Queries on the table now read from the cache, and the plan says so:

from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()

print(spark.sql("""
EXPLAIN
SELECT name FROM emp_parquet WHERE salary > 60000
""").first()[0])
== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [name#3585]
   +- Filter (isnotnull(salary#3587) AND (salary#3587 > 60000))
      +- Scan In-memory table emp_parquet [name#3585, salary#3587], [isnotnull(salary#3587), (salary#3587 > 60000)]
            +- InMemoryRelation [emp_id#3584, name#3585, dept#3586, salary#3587, hire_date#3588, manager_id#3589, city#3590], StorageLevel(disk, memory, deserialized, 1 replicas)
                  +- ...

Scan In-memory table and InMemoryRelation replace the Parquet FileScan. StorageLevel(disk, memory, ...) shows the cache uses memory first and spills to disk.

Release the memory when you are done:

UNCACHE TABLE emp_parquet

You can also cache the result of a query under a new name. LAZY delays the caching until the first query uses it:

CACHE LAZY TABLE high_earners AS
SELECT * FROM emp_parquet WHERE salary > 60000
SELECT COUNT(*) AS n FROM high_earners
+---+
|n  |
+---+
|4  |
+---+

Four employees earn more than 60000, and that result is now cached as high_earners. When you are finished, CLEAR CACHE removes everything from the cache at once:

CLEAR CACHE

Common mistake: Caching everything "to make it faster". Caching costs time (the first read plus writing to memory) and memory that your joins and aggregations also need. Cache only data you reuse several times, and uncache it afterwards.


11. Table Statistics with ANALYZE TABLE

Spark makes better choices, such as whether a table is small enough to broadcast, when it knows how big tables are. ANALYZE TABLE computes statistics and stores them in the catalog:

ANALYZE TABLE emp_parquet COMPUTE STATISTICS

Add FOR COLUMNS to also collect per-column statistics such as minimum, maximum, null count and number of distinct values:

ANALYZE TABLE emp_parquet COMPUTE STATISTICS FOR COLUMNS salary, dept

DESCRIBE EXTENDED table column shows what was collected:

DESCRIBE EXTENDED emp_parquet salary
+--------------+----------+
|info_name     |info_value|
+--------------+----------+
|col_name      |salary    |
|data_type     |int       |
|comment       |NULL      |
|min           |45000     |
|max           |95000     |
|num_nulls     |0         |
|distinct_count|6         |
|avg_col_len   |4         |
|max_col_len   |4         |
|histogram     |NULL      |
+--------------+----------+

Column statistics are mainly used by the cost-based optimizer (for example, to choose a join order), which is off by default in Spark 3.5:

SET spark.sql.cbo.enabled
+---------------------+-----+
|key                  |value|
+---------------------+-----+
|spark.sql.cbo.enabled|false|
+---------------------+-----+

Statistics are a snapshot. After large writes to a table, run ANALYZE TABLE again, or Spark will plan with outdated numbers.


12. Try It in the Online Compiler

Copy this into the PySpark Online Compiler. It builds a small table, then prints a few plans to compare:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL EXPLAIN").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000), (2, 'Ben',   'Engineering', 82000),
  (3, 'Chen',  'Sales',       60000), (4, 'Divya', 'Sales',       65000),
  (5, 'Elena', 'Marketing',   58000), (6, 'Farid', 'Engineering', 82000),
  (7, 'Grace', NULL,          45000)
AS employees(emp_id, name, dept, salary)
""")
spark.sql("""
CREATE OR REPLACE TEMP VIEW departments AS
SELECT * FROM VALUES ('Engineering', 'Floor 3'), ('Sales', 'Floor 1'), ('Marketing', 'Floor 2')
AS departments(dept, location)
""")

# A GROUP BY: look for the Exchange (shuffle) between the two HashAggregate steps
print(spark.sql("""
EXPLAIN
SELECT dept, COUNT(*) AS n FROM employees GROUP BY dept
""").first()[0])

# A join with a hint: look for BroadcastHashJoin
print(spark.sql("""
EXPLAIN
SELECT /*+ BROADCAST(d) */ e.name, d.location
FROM employees e JOIN departments d ON e.dept = d.dept
""").first()[0])

# The same join, forced to sort-merge: look for SortMergeJoin and two Exchange steps
print(spark.sql("""
EXPLAIN
SELECT /*+ MERGE(e, d) */ e.name, d.location
FROM employees e JOIN departments d ON e.dept = d.dept
""").first()[0])

Summary

  • EXPLAIN query shows the physical plan without running the query. EXTENDED adds the parsed, analyzed and optimized plans; FORMATTED gives a numbered outline with details; COST adds size statistics.
  • Read plans bottom up. In a FileScan, ReadSchema shows column pruning and PushedFilters shows filter pushdown.
  • Exchange means a shuffle, usually the most expensive step. GROUP BY uses a partial aggregate before the shuffle to send less data.
  • Join hints (BROADCAST, MERGE, SHUFFLE_HASH) and partitioning hints (REPARTITION, COALESCE, REBALANCE) go in a /*+ ... */ comment after SELECT.
  • SET key = value changes settings such as spark.sql.shuffle.partitions; RESET restores defaults.
  • CACHE TABLE keeps reused data in memory; UNCACHE TABLE and CLEAR CACHE release it. ANALYZE TABLE ... COMPUTE STATISTICS helps Spark plan with real sizes.

That completes the Spark SQL series. Put it into practice with the coding interview questions, which you can solve with spark.sql() in the online compiler.