Cost-Based Optimization

Concepts covered: Catalyst Optimizer

The logical rules fire on the shape of the tree alone. Other choices need sizes: how many rows survive a filter, how many groups an aggregate yields, which of 2 inputs is the small one. For those, Catalyst attaches a Statistics estimate to every logical operator. Cost-based optimization covers how the estimates are computed and what is decided from them. With spark.sql.cbo.enabled at its default of false, Spark estimates byte sizes only.

Where the numbers come from

StatisticWhere Spark gets itThere without ANALYZE?
Size in bytes of a file tableTotal size of its filesYes
Row countANALYZE TABLE ... COMPUTE STATISTICSNo
Distinct count, null count, average and max lengthANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNSNo
Min and maxThe column command, for numeric, date and timestamp columnsNo
HistogramThe column command with spark.sql.statistics.histogram.enabled on, same typesNo
from pyspark.sql import functions as F

spark.sql("ANALYZE TABLE orders COMPUTE STATISTICS FOR COLUMNS status, profit")
spark.conf.set("spark.sql.cbo.enabled", "true")

completed = spark.table("orders").filter(F.col("status") == "Completed")
completed.explain(mode="cost")

explain(mode="cost") prints the optimized logical plan with a Statistics(sizeInBytes=..., rowCount=...) entry on every line: the numbers the planner acts on.

Estimates with and without column statistics

Without column statistics, Spark propagates bytes alone, and its assumption for a filter is that every row survives: the filtered table is estimated at the full table's size. A Project scales the bytes by how much narrower its rows are, and an aggregate with no grouping keys is estimated at 1 row. With CBO on and column statistics present, Spark estimates what fraction a filter keeps. An equality test on a string keeps the row count divided by the distinct count. A range test on a number assumes values spread evenly between min and max, and tests joined by AND multiply their fractions.

Take an orders table of 40,000,000 rows in 1.6 GB of files, where status has 4 distinct values and profit runs from -50 to 950. In the real data, 28,000,000 orders are completed.

Plan stepBytes onlyCBO with column statsReal rows
Relation orders1.6 GB40,000,000 rows40,000,000
Filter status = 'Completed'1.6 GB10,000,000 rows28,000,000
Filter profit > 1001.6 GB34,000,000 rows31,000,000
Both filters, joined by AND1.6 GB8,500,000 rows24,000,000

The status estimate misses because strings get no histogram, so Spark gives each of the 4 values an equal share while most real orders complete. The AND row misses for a second reason: Spark multiplies the fractions as if the 2 tests were unrelated, when completed orders are the ones that carry profit. Neither error is visible until a decision built on the estimate goes wrong.

CBO is on and orders was analyzed for columns this morning, with no rows added since. It holds 10,000,000 rows, and status has 5 distinct values and no nulls. What row count does Spark estimate for orders.filter(F.col("status") == "Cancelled")?

Statistics that go stale

Statistics are a snapshot saved in the catalog when ANALYZE runs. When Spark itself writes to the table, it discards the snapshot, or recomputes the size alone if spark.sql.statistics.size.autoUpdate.enabled is on. Files added by another process leave the old snapshot in place, and the planner trusts it: a table analyzed at 40,000,000 rows that has since tripled still plans as 40,000,000.

Do
  • Re-run ANALYZE after loads that change a table's size or the spread of its values
  • Collect column stats on the columns your filters and grouping keys use
  • Read explain(mode="cost") when a plan choice surprises you
Avoid
  • Switch on spark.sql.cbo.enabled for unanalyzed tables and expect a change
  • Trust a distinct-count estimate on a column where 1 value dominates
  • Let other processes add files to a table whose stats the planner still reads

The cell measures the practice orders the way column statistics would. Divide total_rows by distinct_statuses to get the estimate for status = 'Completed', then set it beside completed_rows, the real count. The gap is the error any plan built on that estimate would carry.

About this lesson

This section is part of the Catalyst Optimizer: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.