Sub topic 10
Checking file counts, sizes, and query pruning
This chapter covers how to tell whether a Delta table's layout is healthy, and how to confirm that an optimization changed anything. It assumes you can run SQL and Python in a Databricks notebook, know what a Delta transaction log is, and have read the earlier chapters on small files, data skipping, and OPTIMIZE. Tuning a layout without measuring it is guesswork. You need three measurements: the state of the table, the history of changes to it, and what a specific query actually read.
What to measure
A layout can fail in two separate ways. Each failure shows up in a different place.
| Question | Symptom | Where to look |
|---|---|---|
| Are there too many small files? | Slow scans even on selective queries, high task counts | `DESCRIBE DETAIL`, `DESCRIBE HISTORY` |
| Are queries skipping files? | Selective filters still read most of the table | Query profile, Spark UI, `EXPLAIN` |
| Did maintenance work? | Same numbers before and after `OPTIMIZE` | Before/after comparison of both |
Reading table state with DESCRIBE DETAIL
DESCRIBE DETAIL returns one row of metadata about the current version of the table. These columns matter for layout work:
numFiles: the number of data files referenced by the current table version.sizeInBytes: the total size of those files.partitionColumns: the Hive-style partition columns, if any.clusteringColumns: the liquid clustering columns, if any.
DESCRIBE DETAIL events;Divide sizeInBytes by numFiles to get the average file size. A table with 50,000 files and 20 GB of data averages about 400 KB per file. That is a clear small-files problem. A table with 20 files and 20 GB averages 1 GB per file, which is healthy for compaction purposes.
You can compute this directly in a notebook:
from pyspark.sql import functions as F
detail = spark.sql("DESCRIBE DETAIL events")
(detail
.select(
"numFiles",
F.round(F.col("sizeInBytes") / 1024 / 1024, 1).alias("size_mb"),
F.round(F.col("sizeInBytes") / F.col("numFiles") / 1024 / 1024, 2).alias("avg_file_mb"),
"partitionColumns",
"clusteringColumns",
)
.show(truncate=False))There is no single correct average file size. As a working guide, files in the hundreds of megabytes are normal for large tables. OPTIMIZE aims for files of up to about 1 GB, and it may choose smaller targets for small tables. Averages in the tens of kilobytes or low megabytes on a large table deserve investigation.
Limits of DESCRIBE DETAIL
- It reports the current snapshot only. Files that earlier operations removed from the table, but that still sit in storage, are not counted. Storage can therefore be larger than
sizeInBytesuntilVACUUMruns. - An average hides the distribution. A table with a few huge files and thousands of tiny ones can show a respectable mean. Use the per-operation file statistics in the history (next section) to see min, max, and average sizes.
- For a partitioned table, the totals cover all partitions. One hot partition full of small files can be invisible in the table-wide average. To find it, count files per partition.
Reading the change log with DESCRIBE HISTORY
DESCRIBE HISTORY lists each commit to the table, with the operation name, a timestamp, and an operationMetrics map. It answers two questions. Which writes are creating small files? And what did the last OPTIMIZE change?
history = spark.sql("DESCRIBE HISTORY events")
(history
.select("version", "timestamp", "operation", "operationMetrics")
.orderBy("version", ascending=False)
.limit(10)
.show(truncate=False))Look at the metrics for two kinds of operations.
- Write operations such as
WRITE,MERGE,STREAMING UPDATE, andUPDATE. Metrics typically include the number of files added and removed, and the rows written. A streaming job that commits every few seconds and adds a handful of tiny files each time appears as hundreds of consecutive versions with small file counts. This is the usual source of small files. OPTIMIZEoperations. Metrics report how many files were removed and added, and the byte totals. The exact metric names vary by runtime version, so print the map once and read the names your workspace uses. In a healthy compaction, the files-removed count is much larger than the files-added count, and the average size of the added files is much larger than that of the removed files.
To isolate maintenance commits, filter on the operation column:
(spark.sql("DESCRIBE HISTORY events")
.filter("operation = 'OPTIMIZE'")
.select("version", "timestamp", "operationMetrics")
.show(truncate=False))If OPTIMIZE appears with zero files removed, the table was already compact for that run. If it never appears, nothing has compacted the table since it was created, unless auto compaction or predictive optimization is doing the work. Those commits can appear under a different operation name, so check the names in your history.
Measuring query pruning
Table-level numbers describe the layout. They do not tell you whether a query benefits from it. Data skipping works per query. Delta keeps per-file minimum and maximum values for columns in the transaction log. Before reading, the engine drops every file whose range cannot match the filter. You want to see how many files were dropped.
In the query profile
Run the query in a SQL warehouse or notebook, then open its query profile (or the Spark UI SQL tab). In the scan node for your table, look for metrics such as files read, files pruned, and the size of files read. Labels differ between Databricks releases. The idea is the same: compare the files and bytes actually scanned with the table total from DESCRIBE DETAIL.
For example, if numFiles is 2,000 and a query filtering on one user_id reads 1,950 files, pruning is nearly useless. If it reads 12 files, pruning works.
Controlling the experiment
Time alone is a weak signal. A second run of the same query is often faster because of the disk cache, not because of the layout. Use this procedure:
- Pick two or three queries that represent real workloads, with the filters users actually apply.
- Record files read, bytes read, and elapsed time for each, on the same compute size.
- Apply one layout change.
- Re-run the same queries and compare files and bytes first. Use time only as a secondary signal, and ignore a first run that warmed the cache.
Change one thing at a time. If you add ZORDER BY and enable auto compaction in the same step, you cannot tell which one helped.
Why pruning can fail
When a selective filter still reads most files, check these causes in order:
- The filter column has no statistics. By default, Delta collects statistics on the first 32 columns of the schema (
delta.dataSkippingNumIndexedCols). A filter column beyond that position, or a long string column, may have no usable min/max values. - The data is not co-located. If every file contains a wide range of
user_idvalues, every file's min/max range overlaps the filter. Compaction alone does not fix this. You needZORDER BYor liquid clustering on that column. - The filter is not prunable. Wrapping the column in a function, or comparing it to a value after a cast, can prevent the engine from comparing it against file ranges. Rewrite the predicate so the bare column is compared with a literal.
- The layout is stale. New data written since the last
OPTIMIZEis not clustered. Check the history for the lastOPTIMIZEversion and how much data was written after it.
EXPLAIN FORMATTED
SELECT COUNT(*) FROM events WHERE user_id = 42;EXPLAIN shows the filters pushed down to the scan. If your predicate is missing from the pushed filters, the engine cannot use it for skipping.
A before-and-after record
Keep a simple log for each experiment. Here is one example for an events table where queries filter on user_id:
| Step | numFiles | Avg file size | Files read for `user_id = 42` |
|---|---|---|---|
| Baseline | 48,000 | 0.4 MB | 47,500 |
| After `OPTIMIZE` | 22 | 880 MB | 22 |
| After `OPTIMIZE ... ZORDER BY (user_id)` | 22 | 880 MB | 3 |
The numbers are illustrative. They show the pattern: compaction cuts the file count and the per-file overhead, and co-location cuts the number of files read for a selective filter. Without the third row, you would not know that compaction alone left the scan reading every file.
Exercise
A table has numFiles = 30,000 and sizeInBytes = 15 GB. A query that filters on customer_id reads 29,800 files. You run OPTIMIZE, and numFiles drops to 20, but the same query now reads all 20 files. What does this tell you, and what should you check or change next?
Show answer
The average file size was about 0.5 MB before compaction, so OPTIMIZE fixed the small-files problem. The query still reads every file, which means pruning is not working. Compaction does not group rows by value. Each file still spans a wide range of customerid values. Check that customerid has file statistics (it is within the first 32 columns, or the indexed-column setting covers it) and that the predicate compares the bare column to a literal. Then co-locate the data with OPTIMIZE ... ZORDER BY (customerid), or switch to a liquid clustered table with CLUSTER BY (customerid). Re-measure files read for the same query to confirm.
Exercise
Why is DESCRIBE DETAIL alone not enough to check that an OPTIMIZE run was effective, and which other output would you add?
Show answer
DESCRIBE DETAIL shows only the current snapshot, so it cannot show what the run changed or the spread of file sizes. Add DESCRIBE HISTORY to see the files removed and added by the OPTIMIZE commit. Add the query profile for a representative query to see whether files read dropped.