Sub topic 9
Data skipping: reading fewer files
This chapter assumes you know basic SQL, have used Delta tables in a Databricks workspace, and understand that a Spark query runs as stages and tasks that read files. The previous chapter covered file layout and OPTIMIZE. Here you will see how Delta Lake uses file-level statistics to avoid reading files at all, and how to check whether it is working.
Why reading fewer files matters
A scan is often the most expensive part of a query. Photon and Spark can process data quickly, but the fastest bytes are the ones never read. Data skipping lets the engine rule out whole files before it opens them.
Delta Lake stores a transaction log next to the data files. For each data file, the log records statistics, including:
- The number of rows in the file.
- The minimum and maximum value of each of the first columns in the table.
- The count of null values for each of those columns.
When a query has a filter such as WHERE order_date >= '2024-01-01', the engine compares the filter against each file's minimum and maximum values. If a file's maximum order_date is 2023-12-31, no row in it can match, so the file is skipped. The comparison reads only the log, not the data files.
Skipping is conservative. A file is skipped only when the statistics prove it cannot match. If the range overlaps the filter, the file is read, even if only one row matches.
What makes skipping effective
Skipping works by value ranges, so it only helps when each file covers a narrow range of the filtered column. Consider two layouts of the same 1,000 files holding order data.
- Clustered by date. Each file holds one or two days. A filter on one week touches a handful of files. The rest are skipped.
- Random order. Every file holds rows from the whole year. Each file's minimum and maximum span the full range, so no file can be ruled out.
The statistics are identical in kind. The difference is how well the data is arranged. Data written in time order, such as an append-only event table loaded daily, is often well clustered on its date column by default. Filters on other columns, such as customer_id, usually are not.
Statistics are limited to certain columns
By default, Delta collects statistics on the first 32 columns of the table. Columns past that limit have no min and max values, so filters on them cannot skip files. Two consequences follow:
- Column order in the table definition matters. Put columns you filter on often near the front.
- Long strings are costly to track. Wide string columns, such as free-text payloads, are poor candidates for statistics and are best placed after the columns you filter on, or excluded.
You can change how many columns are tracked with a table property.
ALTER TABLE orders
SET TBLPROPERTIES ('delta.dataSkippingNumIndexedCols' = '8');Setting the value lower reduces the cost of writing statistics. Setting it to -1 collects statistics on all columns. Changing the property affects files written afterward. Existing files keep the statistics they already have, so the change does not rewrite old data on its own.
Improving skipping with layout
When data is not naturally ordered by the filtered column, you rearrange it. The next chapter covers partitioning, Z-ordering and liquid clustering in detail. The core idea is shown here because it is how you act on what you learn from skipping metrics.
OPTIMIZE orders;
OPTIMIZE orders ZORDER BY (customer_id);OPTIMIZE compacts small files. ZORDER BY also rewrites the data so that rows with similar customer_id values land in the same files. After that, each file's min and max for customer_id cover a narrower range, and a filter on customer_id can skip most files.
For tables created with liquid clustering, the clustering columns are declared once, and OPTIMIZE applies them.
CREATE TABLE events (
event_id BIGINT,
event_date DATE,
user_id BIGINT,
payload STRING
)
CLUSTER BY (event_date, user_id);
OPTIMIZE events;Checking whether skipping happened
Do not assume skipping worked. Verify it.
In the query plan
Run EXPLAIN FORMATTED on your query and look at the scan node. It lists the pushed filters, which are the predicates the scan can use for skipping.
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;If your filter does not appear among the pushed filters, the scan cannot use it. The plan shows what was pushed down. It does not show how many files were skipped.
In the Query Profile
The Query Profile shows scan metrics for each table. The ones to compare are:
| Metric | What it tells you |
|---|---|
| Files read | Files the scan opened |
| Files pruned | Files skipped through statistics or partitions |
| Bytes read | Data actually read from storage |
| Rows scanned vs. rows output | How selective the scan was |
A healthy skip shows a large number of pruned files against a small number of files read. If the files read equals the total file count despite a selective filter, skipping did nothing. Metric names vary slightly between the Query Profile and the Spark UI, so look for the pair "files read" and "files pruned" or their equivalents.
Common reasons skipping does not work
- The filter column has no statistics. It is beyond the indexed column limit.
- The data is not clustered on the filter column. Every file covers the full range.
- The filter wraps the column in a function. A predicate like
WHERE CAST(order_date AS STRING) = '2024-01-01'orWHERE upper(region) = 'EU'may not compare cleanly with min and max values. Filter on the bare column where you can:WHERE order_date = DATE'2024-01-01'. - The filter has low selectivity. If the query needs 80 percent of the rows, most files must be read anyway.
- Many small files. Statistics exist, but thousands of tiny files each add task overhead. Run
OPTIMIZEfirst. - Types do not match. Comparing a column to a value of a different type can force a cast on the column, which blocks pushdown.
A worked check
Suppose orders has 4,000 files and you run:
SELECT COUNT(*)
FROM orders
WHERE customer_id = 48213;- Run it and open the Query Profile. Say it reads 4,000 files and prunes 0.
- Run
OPTIMIZE orders ZORDER BY (customer_id);. - Run the same query again. Now suppose it reads 12 files and prunes the rest.
- Compare bytes read and wall-clock time, using a warm and a cold run for each, so caching does not distort the comparison.
The numbers in this example are illustrative. Your counts depend on the table's size and data distribution. What matters is the change in files read, not the specific values.
Exercise
A table has 60 columns, and most queries filter on column 45. Skipping on that column prunes no files, even after OPTIMIZE ZORDER BY column 45. What is the most likely cause, and how would you fix it?
Show answer
With default settings, statistics are collected only on the first 32 columns, so column 45 has no min and max values to skip on. Raise delta.dataSkippingNumIndexedCols (or move the column earlier in the table definition), make sure new files are written with the updated setting, and then run OPTIMIZE again so the rewritten files carry statistics for the column.
Exercise
Why might a query with WHERE upper(region) = 'EU' read every file, while WHERE region = 'EU' skips many?
Show answer
File statistics store min and max values of the raw column. The function wrapped around the column prevents the engine from comparing the predicate against those values, so no file can be proven irrelevant. The bare-column filter can be compared directly.