Sub topic 3
Keeping Statistics Useful for the Optimizer
Assume you know basic SQL, Delta tables, and Spark concepts such as stages and tasks. This chapter focuses on decisions that help Photon and Spark choose efficient plans.
Keep statistics useful
The optimizer uses table and column statistics, such as row counts, data size, and value ranges. These statistics help it choose join order and join type.
ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS;Refresh statistics after large changes or schema changes. Verify that your platform's automatic maintenance covers the tables that matter.
Choose join strategies
A broadcast join sends a small table to each executor. The large table avoids a shuffle, which moves data across the network.
SELECT /*+ BROADCAST(c) */ c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
GROUP BY c.region;Use a hint only when the table is reliably small. Broadcasting a large table can exhaust executor memory.
Let adaptive execution handle skew
Adaptive query execution, or AQE, changes parts of a plan while a query runs. It can coalesce small shuffle partitions, change join strategies, and mitigate skew.
Skew occurs when one key contains much more data than other keys. Inspect shuffle read sizes and long-running tasks before changing partition settings.
Use the disk cache
The disk cache stores frequently read remote data on local disks. It can reduce repeated reads, but it does not fix excessive shuffles, poor file layout, or an inefficient join. Test cache benefits with representative repeated workloads.
Replace Python UDFs
A user-defined function, or UDF, is custom code applied to data. Python UDFs can move rows outside the native execution path, limiting Photon optimization.
from pyspark.sql import functions as F
fast = df.withColumn("region_norm", F.upper(F.trim("region")))Prefer built-in functions whenever they express the required transformation.
Automate maintenance
Predictive optimization can automate tasks such as statistics collection and table maintenance, depending on workspace and table configuration. Treat it as an operational aid, not a replacement for checking query profiles and data layout.
Size compute and weigh cost
Photon may finish a workload faster while using a different compute price. Compare total cost, runtime, concurrency, and reliability. A larger cluster is not automatically cheaper if the query is limited by file layout or skew.
Benchmark changes fairly
Run the same query with the same data, filters, compute size, and concurrency. Warm and cold cache runs answer different questions. Record runtime, bytes read, shuffle, spill, and cost. Change one major factor at a time.
Exercise
A broadcast hint makes a query slower and executors run out of memory. What should you do?
Show answer
Remove the hint, verify table statistics, and inspect whether the table is actually small enough to broadcast.