A query ran in four minutes yesterday and takes an hour today. The code and the compute size haven't changed. The query profile shows a huge shuffle, a broadcast of a table that's no longer small, or joins in a strange order. The optimizer is probably planning with missing or outdated row counts.
This runbook confirms that, fixes it and gives you a stopgap if the query can't wait.
Before you start
You need:
- The slow query text and, if possible, the profile of a past fast run.
SELECTon the tables, and an identity allowed to runANALYZEon them (usually the owner or the pipeline's service principal).- A SQL warehouse or cluster other than the one that is struggling.
ANALYZEreads a lot of data.
Two different kinds of statistics are easy to confuse:
| Kind | Used for | Refreshed by |
|---|---|---|
| Delta file statistics (min/max per file) | Skipping files on filters | Writes, or ANALYZE ... COMPUTE DELTA STATISTICS |
| Optimizer statistics (row count, distinct values, nulls) | Join order and join strategy | ANALYZE ... COMPUTE STATISTICS, or predictive optimization |
If the query is slow because it scans too many files, this is the wrong page. Use fixing Delta data skipping.
Step 1: check whether statistics are the problem
Run EXPLAIN on the slow query. It plans the query without executing it:
EXPLAIN
SELECT c.segment, p.category, SUM(f.amount)
FROM sales.gold.fact_orders f
JOIN sales.gold.dim_customer c ON f.customer_id = c.customer_id
JOIN sales.gold.dim_product p ON f.product_id = p.product_id
WHERE f.order_date >= '2026-11-01'
GROUP BY c.segment, p.category;
On Databricks Runtime 16.0 and above, look for the statistics section in the output:
== Optimizer Statistics (table names per statistics state) ==
missing = dim_customer
partial = dim_product
full = fact_orders
Anything under missing or partial is a candidate. For the estimates themselves, run the same query with EXPLAIN COST:
EXPLAIN COST
SELECT COUNT(*)
FROM sales.gold.fact_orders f
JOIN sales.gold.dim_customer c ON f.customer_id = c.customer_id;
Each logical operator shows Statistics(sizeInBytes=..., rowCount=...). No rowCount means there isn't enough information to compute it.
Interpret the result
| What you see | Meaning | Next step |
|---|---|---|
Table listed as missing or partial | Never analyzed, or only some columns analyzed | Step 3 |
full, but the estimate is 10x or more from the actual rows | Statistics exist but are stale | Step 2, then 3 |
full, with accurate scans and a wrong join estimate | Skew or correlated columns | Step 5 |
| Estimates accurate throughout | Not a statistics problem | Check the profile for spill, skew and queueing |
Note
Full statistics can still be stale. Always compare the estimated rows with the actual rows in the query profile or Spark UI.
Step 2: check how old the statistics are
Look at the table-level and column-level values:
-- Table level: find the "Statistics" row
DESCRIBE TABLE EXTENDED sales.gold.dim_customer;
-- Column level: min, max, num_nulls, distinct_count
DESCRIBE TABLE EXTENDED sales.gold.dim_customer customer_id;
-- Actual row count
SELECT COUNT(*) FROM sales.gold.dim_customer;
A NULL distinct_count on a join key means that the column hasn't been analyzed. A row count far from COUNT(*) means the table changed after the last collection.
Then look for the event that moved the data:
SELECT version, timestamp, operation, userName, operationMetrics
FROM (DESCRIBE HISTORY sales.gold.dim_customer)
WHERE operation IN ('WRITE', 'MERGE', 'DELETE', 'CREATE OR REPLACE TABLE AS SELECT', 'RESTORE')
ORDER BY version DESC
LIMIT 20;
Operation names vary by version and command; drop the filter if it hides rows. A backfill, a full reload or a restore just before the slowdown is the usual trigger.
Step 3: refresh the statistics
Analyze only the columns that matter: join keys, filter columns and grouping columns. Start with the tables flagged in step 1.
ANALYZE TABLE sales.gold.dim_customer
COMPUTE STATISTICS FOR COLUMNS customer_id, segment;
ANALYZE TABLE sales.gold.dim_product
COMPUTE STATISTICS FOR COLUMNS product_id, category;
For small tables, collect everything:
ANALYZE TABLE sales.gold.dim_product COMPUTE STATISTICS FOR ALL COLUMNS;
Warning
Column statistics on a wide, multi-terabyte fact table read a lot of data. Run it on separate compute, outside the load window, with named columns only.
Choose the right form:
| Command | Collects | Use when |
|---|---|---|
COMPUTE STATISTICS NOSCAN | Size in bytes | You need a quick size only |
COMPUTE STATISTICS | Row count and size | Table has grown, keys unchanged |
... FOR COLUMNS a, b | Table and named column statistics | Default choice |
... FOR ALL COLUMNS | Table and all column statistics | Small or narrow tables |
COMPUTE DELTA STATISTICS | File-skipping statistics only | You changed the data-skipping columns |
COMPUTE DELTA STATISTICS doesn't refresh optimizer statistics. If you change the skipping columns, run both. The PARTITION clause isn't supported for Delta tables.
Step 4: verify the new plan
- Run the
EXPLAINfrom step 1 again. The tables should be underfull. - Confirm that the join strategy changed, for example from
SortMergeJointo a broadcast join for a small dimension. - Run the query and compare duration, rows and shuffle bytes with the earlier profile.
On a SQL warehouse, rule out cached results before you compare timings:
SET use_cached_result = false;
Then compare runs from query history:
SELECT start_time, total_duration_ms, read_rows, shuffle_read_bytes, spilled_local_bytes
FROM system.query.history
WHERE start_time >= current_timestamp() - INTERVAL 3 DAYS
AND statement_text LIKE '%fact_orders%dim_customer%'
ORDER BY start_time DESC;
Step 5: stopgap when you can't wait
If ANALYZE would take too long, or the estimate stays wrong because of skew, use a hint for this query only:
SELECT /*+ BROADCAST(c) */ c.segment, SUM(f.amount)
FROM sales.gold.fact_orders f
JOIN sales.gold.dim_customer c ON f.customer_id = c.customer_id
GROUP BY c.segment;
Use the alias if the table has one. If the broadcast itself is the problem because the table has outgrown it, ask for a sort merge join:
SELECT /*+ MERGE(c) */ c.segment, SUM(f.amount)
FROM sales.gold.fact_orders f
JOIN sales.gold.dim_customer c ON f.customer_id = c.customer_id
GROUP BY c.segment;
Caution
A
BROADCASThint ignores the size threshold. On a table that keeps growing it can run the driver out of memory and fail every query on that cluster. Add a removal date to the ticket.
Adaptive query execution corrects some bad plans at run time, such as switching to a broadcast join. It doesn't reorder joins, so multi-join queries still depend on good statistics. Don't disable the cost-based optimizer globally to fix one query.
Prevent it next time
For Unity Catalog managed tables, let predictive optimization run ANALYZE for you:
ALTER SCHEMA sales.gold ENABLE PREDICTIVE OPTIMIZATION;
SELECT start_time, catalog_name, schema_name, table_name, operation_type, operation_status
FROM system.storage.predictive_optimization_operations_history
WHERE operation_type = 'ANALYZE'
AND start_time >= current_timestamp() - INTERVAL 14 DAYS
ORDER BY start_time DESC;
Operations are billed, and the history takes time to appear. Check the current prerequisites and documented operation types.
For external tables and anything predictive optimization doesn't cover, add ANALYZE as a task after the load:
TABLES = {
"sales.ext.dim_store": ["store_id", "region"],
"sales.ext.fact_returns": ["order_id", "store_id", "return_date"],
}
for table, cols in TABLES.items():
col_list = ", ".join(f"`{c}`" for c in cols)
spark.sql(f"ANALYZE TABLE {table} COMPUTE STATISTICS FOR COLUMNS {col_list}")
Finally:
- Run
ANALYZEat the end of every backfill, full reload and restore, not only on a schedule. - Keep the column list next to the table definition, and review it when join keys change.
- Alert on duration regressions for critical queries from
system.query.history. - Review join hints each quarter and delete the ones that no longer help.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get