Sub topic 2
Reading Query Plans with EXPLAIN
Prerequisites: basic SQL, Delta Lake tables, and Spark concepts such as stages, tasks, and shuffles.
Reading query plans with EXPLAIN
EXPLAIN shows how Spark plans a query before it runs. EXPLAIN FORMATTED gives a readable physical plan. Read the plan from the bottom upward because lower operators usually produce rows for operators above them.
EXPLAIN FORMATTED
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;Look for these operators:
| Operator | What it means | Possible concern |
|---|---|---|
| Scan | Reads files from a table | Too many files or columns |
| Filter | Removes rows | A filter applied late reads extra data |
| Exchange | Shuffles rows between workers | Network cost and possible spills |
| Join | Combines two datasets | Poor join strategy or skew |
| Aggregate | Computes grouped results | Large shuffle or memory pressure |
The plan describes operators, but the Query Profile shows what happened during execution. Photon support can vary by operator, so use both views when checking whether a query used Photon.
Finding bottlenecks in the Query Profile
In the Query Profile or Spark UI, compare time spent in scans, shuffles, joins, and aggregation. A scan that reads much more data than the query returns often indicates weak data skipping. A large shuffle can indicate an unsuitable join or grouping key. Spilled bytes show that an operator exceeded memory and wrote temporary data to disk.
Delta layout, skipping, and clustering
Delta tables are stored as data files. Many small files increase listing and scheduling overhead. OPTIMIZE compacts small files:
OPTIMIZE orders;Delta records file-level statistics, such as minimum and maximum values. Data skipping uses those statistics to avoid files that cannot match a filter.
Z-ordering co-locates related values in files:
OPTIMIZE orders ZORDER BY (customer_id);Use columns commonly used in selective filters. Avoid partitioning by high-cardinality columns because it creates many directories and small files. For newer tables, liquid clustering provides flexible clustering without fixed partition directories:
CREATE TABLE events (
event_id BIGINT,
event_date DATE,
user_id BIGINT,
payload STRING
)
CLUSTER BY (event_date, user_id);
OPTIMIZE events;Exercise
A query reads 90% of an orders table but returns 1% of its rows. What should you inspect first?
Show answer
Inspect the Query Profile and file statistics, then consider OPTIMIZE and clustering on the filtered columns.