Sub topic 11
Keeping statistics useful for the optimizer
This chapter assumes you can read a basic query plan, know what a Delta table's data files are, and have seen a join and a GROUP BY in a Spark plan. It covers the statistics the optimizer uses, how to collect them, and the errors that make them misleading.
Why the optimizer needs statistics
Spark's optimizer picks a plan by estimating how much data each step produces. It uses those estimates to decide join order, join type (broadcast or shuffle), and how much memory an aggregation may need. If the estimates are wrong, the plan can be wrong. A table that is 50 GB might be treated as 5 MB, or the other way around.
The estimates come from two sources:
- Table-level statistics: the total size in bytes and the row count.
- Column-level statistics: the number of distinct values, the minimum and maximum, the null count, and the average and maximum length for strings and binary columns.
The optimizer that uses these numbers is the cost-based optimizer (CBO). Without column statistics it falls back on size estimates alone. Those are coarse, and they cannot see how selective a filter is.
Two kinds of statistics
Delta tables hold two different sets of statistics. People often confuse them.
| Kind | Where it lives | Who uses it | How it is produced |
|---|---|---|---|
| File-level statistics | In the Delta transaction log, for each data file | Data skipping, which decides which files to read | Written automatically when data is written |
| Table and column statistics | In the metastore | The optimizer, for join order, join type and cardinality estimates | Collected by `ANALYZE TABLE`, or by predictive optimization |
File-level statistics are covered in the data skipping chapter. This chapter is about the second kind. Running ANALYZE TABLE does not change which files a filter can skip, and OPTIMIZE does not refresh the optimizer's column statistics.
Collecting statistics with ANALYZE TABLE
The command below computes table and column statistics for every column.
ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS;You can also limit the work:
-- Table-level only: row count and size in bytes
ANALYZE TABLE orders COMPUTE STATISTICS;
-- Only the columns that appear in joins and filters
ANALYZE TABLE orders COMPUTE STATISTICS FOR COLUMNS customer_id, order_date;Choosing columns saves time on wide tables. A good short list is the columns used in join conditions, in WHERE filters, and in GROUP BY.
The command scans the table, so it costs compute. Run it on a schedule or after large loads, not before every query.
Checking what the optimizer knows
DESCRIBE EXTENDED shows table-level statistics. Look at the Statistics row in the output.
DESCRIBE EXTENDED orders;For one column, ask for its stats directly:
DESCRIBE EXTENDED orders customer_id;The output lists values such as min, max, num_nulls, and distinct_count. If these show NULL, the optimizer has no column statistics for that column.
You can also see the effect in the plan. EXPLAIN COST prints the logical plan with its estimated size and row count for each operator.
EXPLAIN COST
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.region;When statistics are missing, the plan shows only sizeInBytes. When they exist, it also shows rowCount. Compare the estimated row count of an operator with the actual row count you see in the Query Profile. A gap of several orders of magnitude points to bad statistics.
How statistics change a plan
Consider the join in the example. The customers table is small, but the optimizer does not know that unless it has a size estimate. Spark broadcasts a table when its estimated size is below spark.sql.autoBroadcastJoinThreshold. With a correct estimate, customers is broadcast and the large orders table is not shuffled. With a missing or inflated estimate, Spark chooses a sort-merge join and shuffles both sides.
Statistics also affect:
- Join order in queries with three or more tables. The optimizer starts with the join that shrinks the data most.
- Filter selectivity. With min, max and distinct counts, the optimizer can estimate how many rows
order_date >= '2024-01-01'keeps. - Aggregation sizing. Distinct counts help estimate the number of groups.
For the join-type decision itself, see the next chapter on choosing join strategies.
Common errors
Statistics go stale
Statistics describe the table at the time they were collected. After a large load, a delete, or a rewrite, they can be far off. A table that grew from 1 million to 1 billion rows still looks small if nobody re-ran ANALYZE TABLE. The usual symptom is a plan that broadcasts a table that has become too large, or that shuffles one that is now small.
Refresh statistics after large changes in data volume or distribution.
Columns with no statistics
ANALYZE TABLE ... COMPUTE STATISTICS with no column list gives only table-level numbers. The optimizer then cannot estimate selectivity. If the plan from EXPLAIN COST shows no rowCount after a filter, check whether you ran the FOR COLUMNS or FOR ALL COLUMNS form.
Confusing OPTIMIZE with ANALYZE
OPTIMIZE compacts files and can cluster data. It changes the physical layout. It does not collect the metastore statistics the optimizer uses for join planning. Run both when you need both.
Collecting everything on a very wide table
FOR ALL COLUMNS on a table with hundreds of columns is slow, and most of those columns are never filtered or joined. Name the columns that matter.
Fixing a plan with a hint when the statistics are the cause
A BROADCAST hint overrides the optimizer for one query. It works, but it hides the real problem, and it can break later if the small table grows. Fix the statistics first. Use hints when you know something the optimizer cannot learn, or as a short-term measure.
Automating the work
You do not have to schedule ANALYZE TABLE yourself on every table. For Unity Catalog managed tables, predictive optimization can run maintenance operations, including statistics collection, automatically when it decides they are worthwhile. A later chapter covers how to turn it on and what it does. Until you rely on it, treat statistics as something you own: check them after big loads, and re-run ANALYZE TABLE when a plan looks wrong.
A practical routine
- After a large load or rewrite, run
ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNSon join, filter and grouping columns. - Run
DESCRIBE EXTENDEDto confirm the row count and size changed as expected. - Run
EXPLAIN COSTon the slow query and look for missingrowCountvalues. - Compare estimates with actual row counts in the Query Profile.
- Re-test the query. If the join type changed to broadcast, confirm the runtime dropped.
Exercise
A query joins a 2 TB orders table to a customers table that has grown from 10 MB to 40 GB over a year. Nobody has run ANALYZE TABLE since the table was 10 MB, and the plan still broadcasts customers. Why does this happen, and what do you do?
Show answer
The optimizer is using a stale size estimate of about 10 MB, which is under the broadcast threshold, so it chooses a broadcast join. The real table is 40 GB and does not fit in executor memory, so the query is slow or fails. Run ANALYZE TABLE customers COMPUTE STATISTICS FOR COLUMNS on the join and filter columns to refresh the numbers, confirm with DESCRIBE EXTENDED customers, and check that the new plan uses a shuffle-based join. Then schedule the refresh after large loads, or use predictive optimization.
Exercise
You run OPTIMIZE on a table and expect join plans to improve, but EXPLAIN COST still shows no rowCount after a filter. Why?
Show answer
OPTIMIZE compacts files and changes the layout. It does not collect the table and column statistics the optimizer needs for row count estimates. Run ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNS (or FOR ALL COLUMNS) and check EXPLAIN COST again.