Sub topic 4
Compacting Files with OPTIMIZE
This chapter assumes you know basic SQL, can run commands in a Databricks notebook or SQL warehouse, and understand that a Delta table is Parquet data files plus a transaction log. It also assumes you know why many small files slow reads.
What OPTIMIZE does
OPTIMIZE rewrites many small data files into fewer, larger ones. Each file a query touches costs a metadata lookup, a file open, and a task. Fewer, larger files reduce that overhead.
OPTIMIZE does not change table contents. It writes new files and commits a transaction that marks the old files as removed and the new files as added. The old files stay in storage until VACUUM deletes them. Readers that started before the commit keep seeing a consistent snapshot, so OPTIMIZE can run while queries are active.
Diagnose before you compact
Check whether compaction is needed. DESCRIBE DETAIL returns numFiles and sizeInBytes. Dividing the second by the first gives the average file size.
DESCRIBE DETAIL events;If a table holds 50 GB across 100,000 files, the average is about 500 KB. That is far below the file sizes Databricks targets, which are commonly in the hundreds of megabytes to 1 GB range. That table is a good candidate for compaction.
Running OPTIMIZE
The basic form compacts the whole table:
OPTIMIZE events;The command returns metrics, including the number of files added and removed. Compare them with numFiles from DESCRIBE DETAIL before and after.
Limiting work with WHERE
On a partitioned table, you can compact only some partitions. The WHERE clause may reference partition columns only.
CREATE TABLE events_partitioned (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
PARTITIONED BY (event_date);
OPTIMIZE events_partitioned
WHERE event_date >= '2024-01-01';This is useful when old partitions are already compact and only recent ones receive frequent small writes.
Running it from Python
The Delta Python API offers the same operation:
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events")
dt.optimize().executeCompaction()Properties worth knowing
- Idempotent. Running OPTIMIZE again on files that are already compacted does little or no work.
- Incremental. Files that already reached the target size are generally left alone, so repeat runs process mainly new small files.
- Compute cost. OPTIMIZE reads and writes data, so it uses cluster resources. Schedule it for off-peak times where possible.
- Writer conflicts. Because it commits like any other write, it can conflict with concurrent operations that touch the same files. Restricting it with
WHEREreduces that risk.
Common errors
- Expecting storage to shrink right away. The old files remain until
VACUUMremoves them. Storage can grow after OPTIMIZE and fall only after VACUUM. - Filtering on a non-partition column. On a partitioned table, a
WHEREclause on an ordinary column fails. Use partition columns only. - Running it after every small write. Frequent OPTIMIZE jobs waste compute. Later chapters cover optimized writes and auto compaction, which reduce small files at write time.
- Treating it as a fix for poor skipping. Plain compaction merges files but does not arrange rows by value. Co-locating related rows is the job of Z-ordering and clustering.
Exercise
A table has numFiles = 40,000 and sizeInBytes = 20 GB. You run OPTIMIZE, and the file count drops sharply, but your cloud storage bill for the table's location rises. Why, and what clears it?
Show answer
OPTIMIZE wrote new, larger files but did not delete the old ones. They are only marked as removed in the transaction log, so both sets occupy storage. Running VACUUM, once the files are older than the retention period, deletes the unreferenced old files and reclaims the space.
Exercise
Write a statement that compacts only partitions of events_partitioned from 2024-06-01 onward.
Show answer
OPTIMIZE eventspartitioned WHERE eventdate >= '2024-06-01';