Sub topic 3
Data skipping and file statistics
This chapter explains how Delta Lake decides which data files a query can ignore. It assumes you know basic SQL, can run queries in a Databricks notebook or SQL warehouse, and know that a Delta table is Parquet files plus a transaction log. You should also know that a Spark job splits work across tasks.
Why skipping matters
The cheapest file to read is one you never open. A query such as SELECT * FROM events WHERE user_id = 42 could scan every file in the table. Delta Lake avoids this when it can prove from metadata that a file holds no matching rows. Skipping a file saves the cloud storage request, the network transfer, the Parquet decoding, and the task that would have processed it.
This is called data skipping. It does not need an index you build or maintain. It relies on statistics that Delta collects automatically when files are written.
Where the statistics live
Every time a write adds a data file, Delta records an add action in the transaction log (the JSON commit files in _delta_log). That action contains the file path, its size, and a stats field. The stats field is a JSON string with these entries:
numRecords: the number of rows in the file.minValues: the smallest value of each indexed column in the file.maxValues: the largest value of each indexed column in the file.nullCount: the number of nulls in each indexed column.
Because the statistics sit in the log, the query planner reads them without opening any Parquet file. For a table with thousands of files, it reads a few log files and a checkpoint instead.
A single add action looks roughly like this (shortened):
{
"add": {
"path": "part-00000-1a2b.snappy.parquet",
"size": 104857600,
"stats": "{\"numRecords\":500000,\"minValues\":{\"user_id\":1,\"event_date\":\"2024-01-01\"},\"maxValues\":{\"user_id\":9999,\"event_date\":\"2024-01-31\"},\"nullCount\":{\"user_id\":0,\"event_date\":0}}"
}
}How a query uses the statistics
When a query has a filter, the planner compares the predicate with each file's minimum and maximum. If the predicate cannot be true for any value between them, the file is skipped.
The diagram below shows that flow.
Skipping is conservative. A file is skipped only when the statistics prove it cannot match. If the statistics are missing or the predicate is not supported, the file is read. Data skipping never changes query results. It only changes how much work is done.
A worked example
Suppose events has four files, and the query is WHERE user_id = 5200. The statistics for user_id are:
| File | min user_id | max user_id | Read for `user_id = 5200`? |
|---|---|---|---|
| A | 1 | 9,990 | Yes, 5200 is inside the range |
| B | 3 | 9,998 | Yes |
| C | 2 | 9,999 | Yes |
| D | 1 | 9,995 | Yes |
Every file is read. Each file's range covers almost the whole domain, so no file can be excluded. This is what happens when rows arrive in random order with respect to user_id, which is common for tables fed by streaming or many parallel writers.
Now the same rows after they are laid out so that similar user_id values are stored together:
| File | min user_id | max user_id | Read for `user_id = 5200`? |
|---|---|---|---|
| A | 1 | 2,500 | No |
| B | 2,501 | 5,000 | No |
| C | 5,001 | 7,500 | Yes |
| D | 7,501 | 9,999 | No |
One file is read instead of four. The statistics are the same kind in both tables. The difference is how tightly each file's range is bounded. Later chapters cover how OPTIMIZE ... ZORDER BY and liquid clustering produce the second layout. For now, remember that statistics only help when value ranges across files overlap little.
What data skipping can and cannot use
Skipping works on predicates that can be compared with a min/max range. These include:
- Equality and inequality:
=,<,<=,>,>=. INlists andBETWEEN.IS NULLandIS NOT NULL, usingnullCount.LIKE 'prefix%', which behaves like a range on the prefix.- Combinations with
ANDandOR.
It is much less effective in these cases:
- The filter wraps the column in a function, such as
WHERE upper(country) = 'DE'orWHERE year(event_date) = 2024. Rewrite these as ranges on the raw column, for exampleevent_date >= '2024-01-01' AND event_date < '2025-01-01'. - The filter is on a column with no statistics. See the next section.
- The filter has a leading wildcard, such as
LIKE '%abc'. - The values in each file are spread across the full domain, as in the first example above.
Which columns get statistics
Collecting statistics costs write time and log size, so Delta does not index every column. By default it collects them for the first 32 columns of the table schema. Nested fields count individually toward the limit, so a wide struct near the front can use up the budget quickly.
Two properties control this:
delta.dataSkippingNumIndexedColssets how many leading columns are indexed.delta.dataSkippingStatsColumnslists the columns to index by name. It overrides the count and is available on recent Databricks Runtime versions.
ALTER TABLE events SET TBLPROPERTIES (
'delta.dataSkippingStatsColumns' = 'event_id,user_id,event_date'
);Listing the columns you filter on keeps statistics focused. It also lets you leave out wide, long-string columns such as payload, where statistics cost more and rarely help.
Some details that cause surprises:
- Strings are truncated. Minimum and maximum values for string columns are stored using only the first 32 characters or so. Long strings that share a long prefix, such as URLs, give poor ranges.
- Existing files keep their old statistics. Changing these properties affects files written afterward. On recent runtimes you can recompute statistics for existing files with
ANALYZE TABLE events COMPUTE DELTA STATISTICS. Otherwise, files rewritten byOPTIMIZEor other writes pick up the new settings. - Column order matters. If a column you filter on is the 40th in the schema and you have not changed the defaults, it has no statistics. Put frequently filtered columns early, or list them explicitly.
- Type matters. Numbers, dates, and timestamps give compact, useful ranges. High-cardinality strings and binary data give weaker ones.
Looking at the statistics yourself
You can read the statistics from the log to see why a file was or was not skipped. This sketch reads the JSON commit files. It assumes you have direct read access to the table's storage location. For Unity Catalog managed tables, direct path access may be restricted.
from pyspark.sql import functions as F
location = spark.sql("DESCRIBE DETAIL events").first()["location"]
log = spark.read.json(f"{location}/_delta_log/*.json")
stats = (
log.where("add IS NOT NULL")
.select(
F.col("add.path").alias("path"),
F.get_json_object("add.stats", "$.numRecords").cast("long").alias("rows"),
F.get_json_object("add.stats", "$.minValues.user_id").cast("long").alias("min_user_id"),
F.get_json_object("add.stats", "$.maxValues.user_id").cast("long").alias("max_user_id"),
)
)
stats.orderBy("min_user_id").show(truncate=False)If the printed ranges overlap heavily, a filter on user_id will skip few files. This reads only JSON commits. A table with many commits also has Parquet checkpoint files, which this sketch ignores, so treat it as a diagnostic and not an exact current file list. Use DESCRIBE DETAIL events for the current numFiles and sizeInBytes.
To see the effect on a real query, open the query profile in Databricks. The scan node reports how many files were read and how many were pruned. Compare these before and after a layout change.
Common mistakes
- Assuming statistics exist for every column. Check the column position and the two properties above.
- Filtering through a function. Rewrite the predicate as a range on the raw column.
- Expecting skipping to work on randomly ordered data. Wide, overlapping ranges defeat it. Fix the layout, not the query.
- Changing the stats columns and expecting old files to change. Only new or rewritten files get the new statistics, unless you recompute them.
- Many tiny files. Statistics are per file. A table with many small files has more entries to evaluate, and each file that is read has a fixed overhead. The next chapters on
OPTIMIZEaddress this.
Exercises
Exercise
A table has columns ordered as id, name, and then 40 more columns, with filter column region at position 45. Queries filtering on region skip no files. Give two ways to fix this.
Show answer
With the default of 32 indexed columns, region has no statistics, so the planner cannot skip files. One fix is to list it with delta.dataSkippingStatsColumns (for example 'id,region'). Another is to raise delta.dataSkippingNumIndexedCols above 45. Since existing files keep their old statistics, rewrite the files (for example with OPTIMIZE) or recompute statistics with ANALYZE TABLE ... COMPUTE DELTA STATISTICS.
Exercise
Four files each have min userid near 1 and max userid near 10,000. A query filters on user_id = 777. How many files are skipped, and what does this tell you about the table layout?
Show answer
None are skipped, because 777 falls inside every file's min/max range. The rows are not co-located by userid, so the ranges overlap. The fix is a layout that clusters similar userid values in the same files, such as Z-ordering or liquid clustering on user_id.
Exercise
Why is WHERE year(event_date) = 2024 a poor filter for data skipping, and how would you rewrite it?
Show answer
The statistics are stored for event_date, not for year(event_date), so the planner cannot compare the predicate with a min/max range. Rewrite it as WHERE event_date >= '2024-01-01' AND event_date < '2025-01-01'.