Saturday
After running OPTIMIZE on a large Delta table, the number of files may reduce significantly, but the actual query execution time does not improve much.
What could be the reason for this?
How do we determine whether the performance issue is related to file sizes, poor data skipping, inefficient joins or the choice of clustering columns?
Is there a recommended way to measure the actual benefit of running OPTIMIZE?
Saturday
Hi @dataumer ,
OPTIMIZE on its own does bin-packing. It turns many small files into fewer, larger ones, which helps when the problem really was small files. It doesn't change how the data is spread across those files. If the values your queries filter on are scattered across every file, the query still has to read almost all of them, just in bigger pieces. Bin-packing is also idempotent, so running it again on the same data does nothing. On Unity Catalog managed tables with predictive optimization, OPTIMIZE may already be running on its own, so a manual run may not have much left to do.
What makes queries read fewer files is data skipping, and that depends on two things:
To find where the time actually goes, open the query profile. The Top operators panel shows the slowest operators, and the filter icon on the scan shows what percentage of the data was pruned. If the scan dominates and pruning is low, it's a layout or statistics problem. If most of the time is in shuffle or join operators, OPTIMIZE won't change much, and the join strategy is where to look.
To measure the benefit, compare the same queries before and after in system.query.history:
SELECT start_time, total_duration_ms, read_files, pruned_files, read_bytes, shuffle_read_bytes, read_io_cache_percent, from_result_cache FROM system.query.history WHERE statement_text ILIKE '%my_table%' AND execution_status = 'FINISHED' AND start_time >= current_timestamp() - INTERVAL 14 DAYS ORDER BY start_time;
A real gain shows up as more pruned_files and less read_bytes, not just a lower duration. Check read_io_cache_percent and from_result_cache too, so a run served from cache doesn't look like an OPTIMIZE win. Note that statement_text is redacted unless you're an account admin or in the databricks_pii_access group.
OPTIMIZE
Data skipping
Liquid clustering
Query profile
Query history system table
Saturday
Adding further to the points above, I would approach this as Assess → Optimize → Validate, rather than running OPTIMIZE routinely.
1. Assess whether OPTIMIZE is needed
Start with table metadata and previous maintenance history:
DESCRIBE DETAIL catalog.schema.my_table;
DESCRIBE HISTORY catalog.schema.my_table;Check numFiles, sizeInBytes, partitioning, clustering columns and previous OPTIMIZE metrics (numRemovedFiles, numAddedFiles, p50FileSize).
Average file size (sizeInBytes / numFiles) is a useful initial indicator, although it can hide file-size variations.
Another useful feature is Query Performance Insights, available through Query History and Query Profile:
These insights help determine whether compaction is actually required.
2. Distinguish data layout from query planning
An important distinction is that these two commands serve different purposes:
ANALYZE TABLE my_table COMPUTE DELTA STATISTICS;
ANALYZE TABLE my_table COMPUTE STATISTICSThe former updates file-level statistics for data skipping, while the latter collects statistics for the query optimizer. OPTIMIZE alone may not resolve inefficient join plans.
3. Quantify the actual benefit
Use Delta Time Travel to compare the same query against table versions immediately before and after the OPTIMIZE commit, under comparable compute and cache conditions.
To measure file-pruning efficiency:
SELECT
statement_id,
execution_duration_ms,
ROUND(
100.0 * pruned_files_bytes /
NULLIF(pruned_files_bytes + read_files_bytes, 0),
2
) AS pruning_pct,
read_bytes,
shuffle_read_bytes,
spilled_local_bytes
FROM system.query.history
WHERE statement_id IN ('before_id', 'after_id')If file count decreases but pruning efficiency and bytes read remain similar, compaction may have improved file-management overhead without significantly reducing scan volume.
If scan performance improves but overall execution time does not, investigate joins, shuffle, skew and spill.
Ultimately, OPTIMIZE should be evaluated against workload performance and maintenance cost, not just the reduction in file count.
References:
yesterday
OPTIMIZE by default only does bin-packing - it merges small files into evenly sized large files and the operation is idempotent and makes no changes to the data itself. So if your query is slow because it filters on a column and has to read every file anyway, compaction shrinks the file count but not the bytes scanned - each rewritten file still spans nearly the full min/max range of the filter column, so Delta's per-file statistics (min/max, null counts, record counts) cannot skip anything. Data skipping only works when similar values are physically co-located and plain bin-packing does not reorder rows. Other reasons queries don't speed up after OPTIMIZE is that the workload is not filter driven (full table aggregations were never file bound), stats are not collected for the column you filter on (only the first 32 schema columns get stats by default and string/timestamp stats are truncated) or the bottleneck is a join/shuffle/skew visible in the Query Profile. You can check the query profile of the slow query before and after OPTIMIZE and compare files read vs files pruned, bytes scanned and shuffle spill. If files pruned stays near zero, it's a data-skipping/clustering problem. The files are not issue if the scan listing overhead dropped.
Use liquid clustering which incrementally colocates data by the filter keys on every write and every OPTIMIZE, lets you change clustering keys later without a full rewrite, and works best on high-cardinality, skewed or evolving filter columns. Run OPTIMIZE (or use predictive optimization on UC managed tables) so compaction and re clustering run on a schedule automatically. Check the optimization properly by running few queries before and after and comparing the profile metrics (files pruned and bytes read)
-- Liquid clustering
CREATE TABLE catalog.schema.sales (
sale_date TIMESTAMP, customer_id BIGINT, amount DECIMAL(10,2)
) CLUSTER BY customer_id;
OPTIMIZE catalog.schema.sales;
-- Old tables without liquid clustering - ZORDER
OPTIMIZE catalog.schema.sales ZORDER BY (customer_id);
yesterday
OPTIMIZE primarily improves the physical layout of a Delta table by compacting small files. However, reducing the number of files does not necessarily reduce the amount of data processed by a query.
I would investigate the following.
1. Compare table metrics before and after OPTIMIZE
DESCRIBE DETAIL catalog.schema.orders; DESCRIBE HISTORY catalog.schema.orders LIMIT 5;
Compare the number of files, total table size and OPTIMIZE operation metrics.
If the file count decreases significantly but the query still scans approximately the same amount of data, file fragmentation may not be the primary bottleneck.
2. Review data skipping and clustering
For example, if a table contains 500 million records and most queries filter by customer_id, simply compacting files may not improve performance significantly.
For a suitable Liquid Clustering table, consider:
ALTER TABLE catalog.schema.orders CLUSTER BY (customer_id); OPTIMIZE catalog.schema.orders;
Clustering can improve data skipping by organizing similar values into fewer files. Choose clustering columns based on frequently used query filters.
3. Inspect the query profile
Compare these metrics before and after optimization:
Number of files and bytes scanned.
Percentage of data pruned.
Scan duration.
Shuffle read and write size.
Disk spill and join execution time.
If joins and aggregations consume most of the execution time, file compaction alone will provide limited improvement.
4. Measure performance under consistent conditions
Run the same query multiple times before and after OPTIMIZE using identical compute configurations and comparable cache conditions.
For SQL warehouses, disable the result cache during benchmarking:
SET use_cached_result = false;
Compare execution time, bytes scanned and files pruned. Also verify that statistics are available for the frequently filtered columns.
My recommendation is to identify whether the bottleneck is related to scanning data or processing data before repeatedly running OPTIMIZE.
OPTIMIZE improves file layout, but it cannot resolve inefficient joins, data skew or expensive aggregations. The clustering example above assumes a compatible table and runtime.
Official references:
Optimize data file layout
Liquid Clustering
Query performance insights
Performance optimization best practices
Saturday
Hi @dataumer ,
OPTIMIZE on its own does bin-packing. It turns many small files into fewer, larger ones, which helps when the problem really was small files. It doesn't change how the data is spread across those files. If the values your queries filter on are scattered across every file, the query still has to read almost all of them, just in bigger pieces. Bin-packing is also idempotent, so running it again on the same data does nothing. On Unity Catalog managed tables with predictive optimization, OPTIMIZE may already be running on its own, so a manual run may not have much left to do.
What makes queries read fewer files is data skipping, and that depends on two things:
To find where the time actually goes, open the query profile. The Top operators panel shows the slowest operators, and the filter icon on the scan shows what percentage of the data was pruned. If the scan dominates and pruning is low, it's a layout or statistics problem. If most of the time is in shuffle or join operators, OPTIMIZE won't change much, and the join strategy is where to look.
To measure the benefit, compare the same queries before and after in system.query.history:
SELECT start_time, total_duration_ms, read_files, pruned_files, read_bytes, shuffle_read_bytes, read_io_cache_percent, from_result_cache FROM system.query.history WHERE statement_text ILIKE '%my_table%' AND execution_status = 'FINISHED' AND start_time >= current_timestamp() - INTERVAL 14 DAYS ORDER BY start_time;
A real gain shows up as more pruned_files and less read_bytes, not just a lower duration. Check read_io_cache_percent and from_result_cache too, so a run served from cache doesn't look like an OPTIMIZE win. Note that statement_text is redacted unless you're an account admin or in the databricks_pii_access group.
OPTIMIZE
Data skipping
Liquid clustering
Query profile
Query history system table
Saturday
Adding further to the points above, I would approach this as Assess → Optimize → Validate, rather than running OPTIMIZE routinely.
1. Assess whether OPTIMIZE is needed
Start with table metadata and previous maintenance history:
DESCRIBE DETAIL catalog.schema.my_table;
DESCRIBE HISTORY catalog.schema.my_table;Check numFiles, sizeInBytes, partitioning, clustering columns and previous OPTIMIZE metrics (numRemovedFiles, numAddedFiles, p50FileSize).
Average file size (sizeInBytes / numFiles) is a useful initial indicator, although it can hide file-size variations.
Another useful feature is Query Performance Insights, available through Query History and Query Profile:
These insights help determine whether compaction is actually required.
2. Distinguish data layout from query planning
An important distinction is that these two commands serve different purposes:
ANALYZE TABLE my_table COMPUTE DELTA STATISTICS;
ANALYZE TABLE my_table COMPUTE STATISTICSThe former updates file-level statistics for data skipping, while the latter collects statistics for the query optimizer. OPTIMIZE alone may not resolve inefficient join plans.
3. Quantify the actual benefit
Use Delta Time Travel to compare the same query against table versions immediately before and after the OPTIMIZE commit, under comparable compute and cache conditions.
To measure file-pruning efficiency:
SELECT
statement_id,
execution_duration_ms,
ROUND(
100.0 * pruned_files_bytes /
NULLIF(pruned_files_bytes + read_files_bytes, 0),
2
) AS pruning_pct,
read_bytes,
shuffle_read_bytes,
spilled_local_bytes
FROM system.query.history
WHERE statement_id IN ('before_id', 'after_id')If file count decreases but pruning efficiency and bytes read remain similar, compaction may have improved file-management overhead without significantly reducing scan volume.
If scan performance improves but overall execution time does not, investigate joins, shuffle, skew and spill.
Ultimately, OPTIMIZE should be evaluated against workload performance and maintenance cost, not just the reduction in file count.
References:
yesterday
OPTIMIZE by default only does bin-packing - it merges small files into evenly sized large files and the operation is idempotent and makes no changes to the data itself. So if your query is slow because it filters on a column and has to read every file anyway, compaction shrinks the file count but not the bytes scanned - each rewritten file still spans nearly the full min/max range of the filter column, so Delta's per-file statistics (min/max, null counts, record counts) cannot skip anything. Data skipping only works when similar values are physically co-located and plain bin-packing does not reorder rows. Other reasons queries don't speed up after OPTIMIZE is that the workload is not filter driven (full table aggregations were never file bound), stats are not collected for the column you filter on (only the first 32 schema columns get stats by default and string/timestamp stats are truncated) or the bottleneck is a join/shuffle/skew visible in the Query Profile. You can check the query profile of the slow query before and after OPTIMIZE and compare files read vs files pruned, bytes scanned and shuffle spill. If files pruned stays near zero, it's a data-skipping/clustering problem. The files are not issue if the scan listing overhead dropped.
Use liquid clustering which incrementally colocates data by the filter keys on every write and every OPTIMIZE, lets you change clustering keys later without a full rewrite, and works best on high-cardinality, skewed or evolving filter columns. Run OPTIMIZE (or use predictive optimization on UC managed tables) so compaction and re clustering run on a schedule automatically. Check the optimization properly by running few queries before and after and comparing the profile metrics (files pruned and bytes read)
-- Liquid clustering
CREATE TABLE catalog.schema.sales (
sale_date TIMESTAMP, customer_id BIGINT, amount DECIMAL(10,2)
) CLUSTER BY customer_id;
OPTIMIZE catalog.schema.sales;
-- Old tables without liquid clustering - ZORDER
OPTIMIZE catalog.schema.sales ZORDER BY (customer_id);
yesterday
OPTIMIZE primarily improves the physical layout of a Delta table by compacting small files. However, reducing the number of files does not necessarily reduce the amount of data processed by a query.
I would investigate the following.
1. Compare table metrics before and after OPTIMIZE
DESCRIBE DETAIL catalog.schema.orders; DESCRIBE HISTORY catalog.schema.orders LIMIT 5;
Compare the number of files, total table size and OPTIMIZE operation metrics.
If the file count decreases significantly but the query still scans approximately the same amount of data, file fragmentation may not be the primary bottleneck.
2. Review data skipping and clustering
For example, if a table contains 500 million records and most queries filter by customer_id, simply compacting files may not improve performance significantly.
For a suitable Liquid Clustering table, consider:
ALTER TABLE catalog.schema.orders CLUSTER BY (customer_id); OPTIMIZE catalog.schema.orders;
Clustering can improve data skipping by organizing similar values into fewer files. Choose clustering columns based on frequently used query filters.
3. Inspect the query profile
Compare these metrics before and after optimization:
Number of files and bytes scanned.
Percentage of data pruned.
Scan duration.
Shuffle read and write size.
Disk spill and join execution time.
If joins and aggregations consume most of the execution time, file compaction alone will provide limited improvement.
4. Measure performance under consistent conditions
Run the same query multiple times before and after OPTIMIZE using identical compute configurations and comparable cache conditions.
For SQL warehouses, disable the result cache during benchmarking:
SET use_cached_result = false;
Compare execution time, bytes scanned and files pruned. Also verify that statistics are available for the frequently filtered columns.
My recommendation is to identify whether the bottleneck is related to scanning data or processing data before repeatedly running OPTIMIZE.
OPTIMIZE improves file layout, but it cannot resolve inefficient joins, data skew or expensive aggregations. The clustering example above assumes a compatible table and runtime.
Official references:
Optimize data file layout
Liquid Clustering
Query performance insights
Performance optimization best practices