Databricks DE ยท Topic 3.1
OPTIMIZE compacts many small files into fewer big ones; ZORDER co-locates related values so queries skip more data. This deep dive walks each with the mechanism and the code.
โธ click to run / reset
Rewrites small files into fewer files near a target size (~1 GB by default, spark.databricks.delta.optimize.maxFileSize). Idempotent and reader-safe (snapshot isolation); scope it with a predicate to keep cost down.
SQL & PySpark
OPTIMIZE main.sales.events; -- whole table OPTIMIZE main.sales.events WHERE event_date >= '2026-06-01'; -- scope = cheaper
from delta.tables import DeltaTable DeltaTable.forName(spark, "main.sales.events").optimize().executeCompaction()
โธ click a layout; you're querying WHERE color = red
ZORDER sorts data along a space-filling curve so similar values land in the same files โ tighter per-file min/max โ more files skipped. Pick the 1โ3 columns you actually filter/join on; it's re-applied on each OPTIMIZE as new data lands.
OPTIMIZE main.sales.events ZORDER BY (event_date, user_id);
(DeltaTable.forName(spark, "main.sales.events") .optimize() .executeZOrderBy("event_date", "user_id"))
Rather than only cleaning up afterward, reduce small files as you write. Both target ~128 MB (vs OPTIMIZE's ~1 GB), trading a little write latency for fewer files.
ALTER TABLE main.sales.events SET TBLPROPERTIES ( 'delta.autoOptimize.optimizeWrite' = 'true', -- ~128 MB files on write 'delta.autoOptimize.autoCompact' = 'true'); -- compact small files after write
OPTIMIZE (and VACUUM/ANALYZE) when it detects benefit โ so often you don't schedule OPTIMIZE yourself (don't double-schedule). External tables aren't covered โ you maintain those manually.OPTIMIZE events ZORDER BY (event_date, user_id) compacts and clusters by the common filters โ dashboards speed up.| OPTIMIZE (bin-pack) | OPTIMIZE โฆ ZORDER | Liquid Clustering | |
|---|---|---|---|
| Fixes small files | โ | โ | โ (incremental) |
| Improves filter skipping | โ | โ (chosen cols) | โ (chosen cols) |
| Idempotent / re-spec | โ idempotent | re-applied each run | key set on table |
| Status | current | older approach | recommended (new tables) |
CLUSTER BY, Topic 3.2) over partitioning/ZORDER. Reach for ZORDER mainly on existing tables not yet on liquid clustering.WHERE to limit scope. ZORDER on too many columns dilutes the benefit (pick 1โ3).OPTIMIZE โฆ ZORDER.