CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 4 · Lesson 23/32

    Adaptive Query Execution (AQE) in Spark

    Describe Adaptive Query Execution (AQE) and its benefits.

    18 min read
    3.33% of exam
    4 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Explain when and how AQE re-optimizes a query plan at runtime, and how this differs from planning before execution
    • Predict how AQE coalesces small post-shuffle partitions and name the properties that control it
    • Describe when AQE converts a sort-merge join to a broadcast hash join, and when it cannot
    • Decide whether AQE will treat a shuffle partition as skewed and split it
    • Read explain() output and the Spark UI to tell which AQE optimizations took effect

    Key concept

    Adaptive Query Execution (AQE) — AQE re-optimizes a Spark SQL query while it is running. At each shuffle or broadcast exchange, Spark replaces its pre-execution size estimates with statistics measured from the stages that have finished, then re-plans the stages that are still to run.

    1.How AQE re-plans a query while it runs

    Spark chooses a query plan before any data moves, using estimates of how big each piece of data will be. Those estimates go wrong when table statistics are missing or stale, when the data is skewed, or deep inside a complex query. A plan built on a bad estimate can pick a slow join strategy, create hundreds of tiny tasks after a shuffle, or leave a few oversized tasks holding up a whole stage. Adaptive Query Execution (AQE) fixes these problems by re-optimizing the plan during execution, based on the actual size of the data.

    That timing is what separates AQE from Catalyst whole-plan optimization, which fixes the plan before execution starts. AQE keeps optimizing after the query has begun, and every decision it makes rests on statistics measured from stages of the current query that have already finished. It does not use estimates computed in advance.

    Re-planning happens at materialization points. Spark pipelines most operators, but a shuffle or broadcast exchange breaks the pipeline: every task producing the exchange output has to finish before the next stage can start. The part of a plan between two such points is a query stage. At a stage boundary, Spark has accurate statistics for every partition and no downstream work has started yet, so it can still change the rest of the plan without throwing away any work.

    The loop works like this. AQE first launches the leaf stages, which depend on no other stage. As stages finish, it writes their runtime statistics back into the logical plan. It then re-runs the optimizer and physical planner, including AQE-specific rules such as partition coalescing and skew-join handling, and launches the next stages whose inputs are ready. This execute, re-optimize, execute cycle repeats until the query is done.

    What a wrong pre-execution estimate causes, and the AQE feature that corrects it
    Problem from a wrong estimateAQE feature
    Too many small tasks after a shuffleDynamically coalesces partitions after shuffle exchange
    Slow join strategy chosen for a side that turns out smallDynamically changes sort merge join into broadcast hash join
    A few oversized tasks hold up the whole stageDynamically handles skew in sort merge join and shuffle hash join
    Parts of the query return no rowsDynamically detects and propagates empty relations

    spark.sql.adaptive.enabled is the master switch for AQE. It has defaulted to true since Apache Spark 3.2.0, so queries get AQE without any code change. AQE only applies to a query that is not a streaming query and that contains at least one exchange (usually from a join, aggregate or window), at least one subquery, or both. A query that qualifies shows AQE in its physical plan as one or more AdaptiveSparkPlan nodes, usually at the root of each main query and subquery. AQE re-optimizes every query it supports, but the result can still be the same plan the optimizer compiled before the run.

    Checkpoint 1 of 9· Check yourself

    A filter cuts one side of a join far more than Spark expected, so the plan made before execution estimates that side as large. With AQE enabled, at what point can Spark first correct the plan using the real size of that side?

    Checkpoint 2 of 9· Exam question

    A data engineer wants to understand how Adaptive Query Execution (AQE) differs from Spark's traditional cost-based optimizer. Which statement correctly describes when AQE takes effect?

    Sources123

    2.Coalescing small shuffle partitions

    The right number of shuffle partitions is hard to set by hand. It depends on the data, and data size changes from one stage to the next. With too few partitions, each task is big enough that sorts and aggregations may spill to disk. With too many, each partition is tiny: Spark makes lots of small network fetches and puts more load on the task scheduler. Very small tasks also get worse I/O throughput and pay scheduling and setup overhead that is large relative to the work they do.

    AQE solves this by starting with a high partition count and merging down. spark.sql.shuffle.partitions sets how many partitions a shuffle writes (200 by default). With coalescing turned on, that number is only a starting count. When the map side of the shuffle finishes, AQE reads the shuffle file statistics and merges adjacent small partitions into larger ones before the next stage launches its tasks. If you want a different starting count for AQE, set spark.sql.adaptive.coalescePartitions.initialPartitionNum. When it is unset, it equals spark.sql.shuffle.partitions.

    A small grouped aggregation used to illustrate partition coalescingsql
    SELECT max(i)FROM tbl GROUP BY j

    Suppose tbl is small and the initial shuffle partition number is five. After local grouping, the partially grouped data is shuffled into five partitions, and three of them are very small. Without AQE, Spark starts five tasks for the final aggregation, one per partition, including the near-empty ones. With AQE, the three small partitions are merged into one, so the final aggregation runs three tasks. A groupBy on a column with only a few distinct values works the same way: most of its 200 post-shuffle partitions are nearly empty, and AQE merges them before the next stage, such as a table write, begins.

    Properties that control post-shuffle partition coalescing
    PropertyDefaultRole
    spark.sql.adaptive.coalescePartitions.enabledtrueTurns coalescing on; it also needs spark.sql.adaptive.enabled to be true
    spark.sql.adaptive.advisoryPartitionSizeInBytes64 MBTarget size Spark aims for when merging small post-shuffle partitions
    spark.sql.adaptive.coalescePartitions.minPartitionSize1MBMinimum size of a partition after coalescing
    spark.sql.adaptive.coalescePartitions.initialPartitionNum(none)Starting partition count before coalescing; falls back to spark.sql.shuffle.partitions

    Coalesced partitions come out close to the advisory size but no larger, and never smaller than the minimum size. To aim for roughly 128 MB per partition, raise spark.sql.adaptive.advisoryPartitionSizeInBytes and keep spark.sql.adaptive.coalescePartitions.enabled at true. If that flag is false, nothing gets merged, whatever the target size. The skew thresholds and the broadcast threshold belong to other AQE features, and changing them does not affect how partitions are merged.

    Checkpoint 3 of 9· Check yourself

    A groupBy on a column with only a few distinct values writes its shuffle with spark.sql.shuffle.partitions left at 200, so most post-shuffle partitions are nearly empty. AQE and partition coalescing are both enabled. What does Spark do before the next stage launches its tasks?

    Checkpoint 4 of 9· Exam question

    A PySpark job performs a wide aggregation: result = (df.groupBy("region") .agg(F.sum("amount").alias("total"))) result.write.mode("overwrite").saveAsTable("agg_totals") The region column has very few distinct values, so many of the 200 shuffle partitions created by the aggregation end up nearly empty. With AQE enabled and default settings, what happens to these shuffle partitions before the write stage runs?

    Checkpoint 5 of 9· Exam question

    A team wants to tune AQE's post-shuffle partition coalescing so that Spark targets roughly 128 MB per coalesced partition instead of the 64 MB default, without changing anything about join or skew handling. Which two configuration properties are directly involved in this behavior? (Choose 2 answers)(Select 2)

    0 of 2 selected

    Sources123

    3.Switching a sort-merge join to a broadcast join

    Spark has two main ways to join large inputs, and AQE can swap one for the other mid-query. A sort-merge join shuffles both sides across the network so matching keys meet in the same partition, sorts each side, and then merges them. A broadcast hash join instead sends a copy of one side to every worker node, so the other side needs no sort. That is why it is usually the fastest join when one side fits comfortably in memory: every node has to hold the whole broadcast side. Spark plans one when the estimated size of a join side is below the broadcast threshold. Estimates can be badly wrong, though. A very selective filter, or a join side built from a chain of complex operators instead of a plain scan, can make a small relation look large, and then the static planner chooses a sort-merge join.

    AQE re-plans the join once it knows the real size of each side. If runtime statistics show a join side below spark.sql.adaptive.autoBroadcastJoinThreshold, AQE converts the sort-merge join into a broadcast hash join. That threshold defaults to the same value as spark.sql.autoBroadcastJoinThreshold, and setting it to -1 turns broadcasting off. After the switch, Spark no longer has to sort both join sides. With spark.sql.adaptive.localShuffleReader.enabled (default true), it also reads the existing shuffle files locally, per mapper, which cuts network traffic.

    Yes, because a runtime switch comes late. AQE may not learn the actual table sizes until it has shuffled both sides of the join, so the cost of that shuffle has already been paid. A broadcast join the optimizer plans before execution usually performs better than one AQE introduces at runtime. If you know one side is small, give Spark a hint. AQE respects query hints the same way static optimization does, and it still applies the dynamic optimizations that the hints don't affect.

    Even when a table is under the threshold, AQE won't always broadcast it. Some join types can't broadcast a particular side; for example, AQE can't broadcast the left side of a LEFT OUTER JOIN. AQE also keeps the sort-merge join when the share of non-empty partitions is below spark.sql.adaptive.nonEmptyPartitionRatioForBroadcastJoin, because most tasks in that join already finish quickly. Join order is another thing AQE leaves alone: it doesn't reorder joins at runtime. Join order comes from the cost-based optimizer, which relies on collected table statistics.

    Checkpoint 6 of 9· Check yourself

    Runtime statistics show that the left side of a LEFT OUTER JOIN is only 5 MB, well below spark.sql.adaptive.autoBroadcastJoinThreshold. Most of its partitions are non-empty, yet AQE keeps the sort-merge join. What is the most likely reason?

    Sources123

    4.Splitting skewed partitions in joins

    Data skew means data is spread unevenly across partitions. In a join, it shows up as one task running long after the others have finished. AQE detects skew automatically from shuffle file statistics. It splits each oversized partition into smaller subpartitions and joins each one to the matching partition from the other side, copying that partition when needed, so the skewed work ends up spread over roughly evenly sized tasks.

    Take table A joined with table B, where A's partition A0 is much larger than its other partitions. Without the optimization, four tasks run the sort-merge join and one of them takes far longer than the rest. With it, A0 is split and five tasks run the join, each taking roughly the same time, so the stage finishes sooner. This applies to sort-merge joins and shuffle hash joins. Broadcast joins are never skew-optimized because they have no shuffle partitions to split.

    Skew join settings and the two tests a partition must pass
    PropertyDefaultMeaning
    spark.sql.adaptive.skewJoin.enabledtrueTurns skew join handling on or off
    spark.sql.adaptive.skewJoin.skewedPartitionFactor5Partition must be larger than this multiple of the median partition size
    spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes256MBPartition must also be larger than this absolute size

    A partition has to pass both tests. The relative test keeps AQE from splitting partitions that are only large because every partition is large. The absolute test keeps it from bothering with partitions that are big compared with the median but still cheap to process. If the Spark UI shows a skewed join stage that AQE left alone, the skewed partitions are probably under one of the thresholds, and lowering the factor or the byte threshold lets AQE catch them. AQE skew handling is automatic and usually performs better than the skew join hint, so it is the first fix to reach for.

    Checkpoint 7 of 9· Check yourself

    In the Spark UI, one task in a sort-merge join stage runs far longer than the others. Its partition is 200 MB, and the median partition is 20 MB. AQE is enabled with default skew settings but did not split the partition. Which change lets AQE handle this skew?

    Sources143

    5.Seeing what AQE changed in the plan

    AQE changes the plan while the query runs, so where and when you look at the plan determines what you see. DataFrame.explain() shows two plans under each AdaptiveSparkPlan node: the initial plan, before AQE applies any optimizations, and the current plan. The node's isFinalPlan flag stays false before and during execution and becomes true when the query finishes. At that point the current plan is the final plan.

    The statistics on each shuffle and broadcast stage tell you whether AQE has measured anything yet. Before and during a stage's run, they carry isRuntime=false and are compile-time estimates. After the stage runs, isRuntime=true and the numbers are runtime measurements. In the Spark UI, the query plan diagram shows the latest plan and updates as the query runs. Nodes that have already run keep their metrics and stay fixed, while nodes that haven't run yet can still change.

    SQL EXPLAIN is the exception. It doesn't run the query, so AQE never gets a chance to re-optimize. Its output shows only the initial plan, which can differ from the plan that actually runs. To see what AQE did, compare the current or final plan against the initial plan and look for these signatures.

    How each AQE optimization appears in the current or final plan
    OptimizationSign in the plan
    Join strategy changeA different physical join node than in the initial plan
    Partition coalescingA CustomShuffleReader node with the Coalesced property
    Skew join handlingA SortMergeJoin node with the isSkew field set to true
    Empty relation propagationA LocalTableScan node with an empty relation field replaces part or all of the plan

    Checkpoint 8 of 9· Match them up

    You compare the final plan from DataFrame.explain() with the initial plan. Match each AQE optimization to the sign it leaves in the final plan.

    Tap a term, then the definition that fits it.

    Checkpoint 9 of 9· Check yourself

    An engineer wants to know if AQE switched a join to a broadcast hash join. They run SQL EXPLAIN on the query, and the output shows a SortMergeJoin. What can they conclude from this output?

    Sources1

    Sources

    (4)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far.”
      ↩︎ How AQE re-plans a query while it runs
      “AQE-applied queries contain one or more AdaptiveSparkPlan nodes, usually as the root node of each main query or sub-query.”
      ↩︎ How AQE re-plans a query while it runs
      “The query isn't a streaming query.”
      ↩︎ How AQE re-plans a query while it runs
      “The target size after coalescing. Coalesced partitions are close to, but no larger than, this size.”
      ↩︎ Coalescing small shuffle partitions
      “Very small tasks have worse I/O throughput and tend to suffer more from scheduling overhead and task setup overhead.”
      ↩︎ Coalescing small shuffle partitions
      “AQE might not switch to a broadcast join until after it shuffles both sides of the join”
      ↩︎ Switching a sort-merge join to a broadcast join
      “For example, AQE can't broadcast the left side of a LEFT OUTER JOIN.”
      ↩︎ Switching a sort-merge join to a broadcast join
      “AQE doesn't reorder joins at runtime.”
      ↩︎ Switching a sort-merge join to a broadcast join
      “AQE treats a partition as skewed only when both of these conditions are true”
      ↩︎ Splitting skewed partitions in joins
      “Use AQE skew join handling. It's automatic and usually performs better than the skew join hint.”
      ↩︎ Splitting skewed partitions in joins
      “SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it.”
      ↩︎ Seeing what AQE changed in the plan
      “The flag is false before and during query execution, and changes to true when the query finishes.”
      ↩︎ Seeing what AQE changed in the plan
      “After the stage runs, isRuntime is true and the statistics are runtime measurements.”
      ↩︎ Seeing what AQE changed in the plan
      “Skew join handling. The plan contains a SortMergeJoin node with the isSkew field set to true.”
      ↩︎ Seeing what AQE changed in the plan
      “Adaptive query execution (AQE) is query re-optimization that occurs during query execution.”
      ↩︎ Key concept
      “At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far.”
      ↩︎ Exam trap 1
      “The target size after coalescing. Coalesced partitions are close to, but no larger than, this size.”
      ↩︎ Exam trap 2
      “AQE might not switch to a broadcast join until after it shuffles both sides of the join”
      ↩︎ Exam trap 3
      “AQE treats a partition as skewed only when both of these conditions are true”
      ↩︎ Exam trap 4
      “SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it.”
      ↩︎ Exam trap 5
      “Some join types can't broadcast one side. For example, AQE can't broadcast the left side of a LEFT OUTER JOIN.”
      ↩︎ Checkpoint
      “Partition coalescing. The plan contains a CustomShuffleReader node with the Coalesced property.”
      ↩︎ Checkpoint
      “SQL EXPLAIN doesn't run the query, so AQE can't re-optimize it. The output shows only the initial plan”
      ↩︎ Checkpoint
    2. 2.
      “which is enabled by default since Apache Spark 3.2.0”
      ↩︎ How AQE re-plans a query while it runs
      “If not set, it equals to spark.sql.shuffle.partitions.”
      ↩︎ Coalescing small shuffle partitions
      “The default value is the same as spark.sql.autoBroadcastJoinThreshold.”
      ↩︎ Switching a sort-merge join to a broadcast join
      “a table that will be broadcast to all worker nodes when performing a join”
      ↩︎ Switching a sort-merge join to a broadcast join
    3. 3.
      “a shuffle or broadcast exchange breaks this pipeline. We call them materialization points”
      ↩︎ How AQE re-plans a query while it runs
      “AQE coalesces these three small partitions into one and, as a result, the final aggregation now only needs to perform three tasks rather than five.”
      ↩︎ Coalescing small shuffle partitions
      “such as the presence of a very selective filter”
      ↩︎ Switching a sort-merge join to a broadcast join
      “broadcast hash join is usually the most performant if one side of the join can fit well in memory”
      ↩︎ Switching a sort-merge join to a broadcast join
      “It then splits the skewed partitions into smaller subpartitions, which will be joined to the corresponding partition from the other side respectively.”
      ↩︎ Splitting skewed partitions in joins
      “This provides a natural opportunity for reoptimization, for it is when data statistics on all partitions are available and successive operations have not started yet.”
      ↩︎ Checkpoint
      “then combine adjacent small partitions into bigger partitions at runtime by looking at the shuffle file statistics”
      ↩︎ Checkpoint
    4. 4.
      “Broadcast joins are never skew-optimized”
      ↩︎ Splitting skewed partitions in joins
      “If the skewed partitions are smaller than the thresholds, adjust spark.sql.adaptive.skewJoin.skewedPartitionFactor and spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes.”
      ↩︎ Checkpoint

    Ready to test yourself?

    Practise the 11 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.