Part 8 · Data layout · Chapter 26
Data skipping, Z-order and space-filling curves
Per-file min/max statistics in the Delta log and Iceberg manifests, how a predicate becomes a file filter, why skipping depends on layout, and how OPTIMIZE ZORDER BY uses range ids, bit interleaving and range partitioning to co-locate several columns; Hilbert curves as the alternative.
After this chapter you should be able to:
- Read a Delta stats record, including tightBounds and string truncation.
- Translate a predicate into the per-file condition Delta evaluates.
- Compute a Z-order value by bit interleaving, and explain why Delta interleaves range ids.
- Estimate skipping for a layout, and compare linear, Z-order and Hilbert layouts.
Partitioning (chapter 25) skips whole directories, but only on a few low-cardinality columns. The finer tool is data skipping. Each data file’s minimum and maximum per column are kept in the table’s metadata, and a planner drops every file whose range cannot satisfy the query. It is the same check as chapter 8’s row-group statistics, one level up, and planning does it without opening a single file.
Statistics only describe a layout; they cannot improve it. A file written from a random slice of the data spans nearly the whole domain of every column and can never be skipped. Making files hold narrow ranges on several columns at once is the job of space-filling curves: Z-order, which OPTIMIZE ZORDER BY uses, and the Hilbert curve, which liquid clustering (chapter 27) uses. The code is in src/sim/layout/zorder.ts.
File statistics in the log
Delta’s add action has an optional stats field, a JSON string with:[PROTOCOL.md: per-file statistics]
{"numRecords": 4096,
"minValues": {"trip_id": 100000, "city": "Austin", "pickup": "2026-03-01T00:00:04.000Z"},
"maxValues": {"trip_id": 104095, "city": "Seattle", "pickup": "2026-03-01T23:59:58.000Z"},
"nullCount": {"trip_id": 0, "city": 0, "pickup": 0},
"tightBounds": true}
The per-column structs mirror the schema, nested fields included. Checkpoints can store the same data as a parsed stats_parsed struct, which is what makes skipping fast on big tables (chapter 11). A few rules matter for correctness:
- Not every column. By default Delta collects stats for the first 32 leaf columns in schema order:
delta.dataSkippingNumIndexedCols, where -1 means all.delta.dataSkippingStatsColumnsnames columns explicitly instead.[Delta DeltaConfig] A filter on column 45 of a 60-column table skips nothing. - Strings are truncated. “String columns are cut off at a fixed prefix length”, 32 characters by default. Timestamps are truncated to milliseconds.[Delta DeltaSQLConf] A truncated max must still be an upper bound. So
truncateMaxStringAggkeeps the prefix and appends\u007Fif the next character sorts below it, and U+10FFFF otherwise.[Delta truncateMaxStringAgg] - Wide bounds after deletes. When a deletion vector hides rows (chapter 13), the stats still describe the physical file.
tightBounds: falsesays the min and max are only bounds on the valid rows, not values that occur in them. “These upper/lower bounds are sufficient information for data skipping”. What weakens isnullCount: it then means something only when it is 0 or equal tonumRecords.
Iceberg keeps the same facts per data file in its manifests: lower_bounds and upper_bounds maps keyed by field id, with null_value_counts and nan_value_counts. Each bound must be “less than or equal to all non-null, non-NaN values in the column for the file”.[Iceberg spec: manifests] The Java library’s default metrics mode is truncate(16), which keeps 16-character bounds. It infers metrics for the first 100 columns (write.metadata.metrics.max-inferred-column-defaults).[Iceberg TableProperties] Chapter 16 covers how Iceberg prunes manifests with partition summaries before it reaches these per-file bounds.
Q1. Where does a Delta reader find the min and max of a column for a data file, without opening it?
Q2. A Delta table has 60 columns and default settings. A query filters on column 45. Can data skipping help?
Q3. A file's stats say tightBounds = false after a DELETE added a deletion vector. Can a reader still skip with minValues and maxValues?
Q4. Delta keeps 32 characters of string stats by default. A file's max is a 40-character URL starting https://shop.example.com/p/shoes/…. What is stored as maxValues?
How a predicate becomes a file filter
Delta’s DataFiltersBuilder rewrites the query’s filter into an expression over the stats columns, and evaluates it against every AddFile in the snapshot. The base cases come from ColumnPredicateBuilder:[Delta DataSkippingPredicateBuilder]
| Query filter | File may match when |
|---|---|
x = v | min <= v AND v <= max |
x <> v | min < v OR v < max |
x < v / x <= v | min < v / min <= v |
x > v / x >= v | max > v / max >= v |
x IS NULL | nullCount > 0 |
a AND b | either side that can be translated |
a OR b | both sides translated, and either may match |
For OR, the source comment explains: “a single leg of an OR expression provides no filtering power — we can only reject a file if both legs evaluate to false”.[Delta DataFiltersBuilder] A file with no stats for a column, or no stats at all, is always kept. The surviving files then go to Parquet, where chapter 8’s row-group statistics and page indexes skip further.
Q1. Which per-file conditions does Delta use to decide a file may match? (Select all.) (select all that apply)
Why layout decides everything
Take 4,096 rows with two columns, x and y, uniform on 0–999, in 64 files. The simulator gives these numbers:
| Layout | x BETWEEN 400 AND 450 | y BETWEEN 400 AND 450 | x 100–250 AND y 600–750 |
|---|---|---|---|
| arrival order | 64 files | 64 | 64 |
sorted by x | 4 | 64 | 11 |
| Z-order on (x, y) | 13 | 17 | 9 |
| Hilbert on (x, y) | 13 | 13 | 5 |
In arrival order, every file covers nearly [0, 999] on both columns, so the statistics prove nothing. A linear sort by x is perfect for x and useless for y: each file holds a narrow band of x and the full range of y. A sort on (x, y) would not help, because y is ordered only within ties of x. A curve gives up some of x’s locality to give both columns some. Each file then covers a compact patch of the plane, and a box query touches only the patches it overlaps.
x BETWEEN 100 AND 250 AND y BETWEEN 600 AND 750. This example uses the book’s 64-file simulation.
Q1. 64 files, each written from a random slice of the data. What fraction of files does WHERE x BETWEEN 400 AND 450 read, with x uniform on 0–999?
Z-order: interleaving bits
The Z-order curve, or Morton order, visits a grid by interleaving the bits of the coordinates. G. M. Morton described it in a 1966 IBM technical report, A Computer Oriented Geodetic Data Base; and a New Technique in File Sequencing (IBM Ltd., Ottawa), for exactly this purpose: ordering records in a file.[Z-order curve: references] Take the most significant bit of each coordinate in turn, then the next bit of each, and so on. For (x, y) = (2, 3) with two bits each, x = 10 and y = 11 give 1 1 0 1 = 13.
Delta’s InterleaveBits does this over all 32 bits of each input and returns 4 × n bytes:[Delta InterleaveBits]
// InterleaveBits.defaultInterleaveBits (trimmed)
var bit = 31 /* going from most to least significant bit */
while (bit >= 0) {
var idx = 0
while (idx < numCols) {
ret_byte = (ret_byte | (((inputs(idx) >> bit) & 1) << ret_bit)).toByte
ret_bit -= 1
if (ret_bit == -1) { ret.update(ret_idx, ret_byte); ret_byte = 0; ret_idx += 1; ret_bit = 7 }
idx += 1
}
bit -= 1
}
Sorting by the resulting bytes walks the plane in Z-shaped quadrants, recursively. Points close on the curve are close in space. The reverse is not always true: the curve jumps at every power-of-two boundary, for example from (1, 3) to (2, 0) on a 4×4 grid. The tests check the Morton order on that grid.
Q1. Z-order interleaves bits most-significant first, taking x then y. What is the Z-value of (x, y) = (2, 3) using 2 bits each?
How OPTIMIZE ZORDER BY works
Interleaving raw column values would not work well. The columns have different types, and a skewed column would put most rows in a few cells. Delta first maps each column to a rank bucket. SpaceFillingCurveClustering.cluster builds the key as:[Delta MultiDimClustering]
// ZOrderClustering.getClusteringExpression
val rangeIdCols = cols.map(range_partition_id(_, numRanges)) // numRanges = 1000 by default
interleave_bits(rangeIdCols: _*).cast(StringType)
// then, in cluster():
df.withColumn(key, mdcCol).withColumn(rand, (rand() * 255 - 128).cast(ByteType))
.repartitionByRange(approxNumPartitions, col(key), col(rand))
The steps, in order:
range_partition_id(col, 1000). The optimizer rewrites this into aRangePartitionerbuilt by sampling the column. Each value becomes the index of its range: 0–999, with ranges of about equal row count, and ties always in the same range.[Delta RangePartitionId] A string, a timestamp and a skewed integer all become evenly spread 10-bit numbers.interleave_bits. The range ids are interleaved into a byte key, and the cast to string keeps a byte-wise ordering.repartitionByRange(approxNumFiles, key, noise). The rows are cut into contiguous ranges of the key, one output file each.approxNumFilesis the bin’s total size divided byoptimize.maxFileSize(1 GiB by default).[Delta OptimizeTableCommand] A random byte is added as a second key (spark.databricks.io.skipping.mdc.addNoise, true by default). The config’s doc says it “can help deal with skew, but may have a negative impact on overall min/max skipping effectiveness”. Rows are not sorted within files unlessmdc.sortWithinFilesis set.[Delta DeltaSQLConf]
Two consequences follow:
- It is not incremental. For compaction, OPTIMIZE picks small files. For Z-order,
filterCandidateFileListreturns early with “Select all files in case of multi-dimensional clustering”. Every run rewrites every file in the partitions it touches.[Delta filterCandidateFileList] On a table that grows daily, each run costs a full rewrite. Liquid clustering (chapter 27) fixes this. - The columns are checked.
validateZorderByColumnsrejects partition columns, which already cluster the data. It also rejects, by default, columns with no statistics, since Z-ordering them could never help skipping.
Q1. Why does OPTIMIZE ZORDER BY interleave range_partition_id(col, 1000) and not the column values themselves?
Q2. You ran OPTIMIZE ZORDER BY (a, b) yesterday, and 5% new data arrived today. What does running it again rewrite in open-source Delta?
Hilbert curves
David Hilbert published his curve in 1891, in “Über die stetige Abbildung einer Linie auf ein Flächenstück”, Mathematische Annalen 38, 459–460.[Hilbert curve: references] It also visits every cell of a 2^k × 2^k grid, but each quadrant is rotated or reflected so that the curve enters it where the previous one ended. Consecutive positions on a Hilbert curve are always adjacent cells, and the tests check this for every step of a 16×16 grid. Z-order has no such guarantee.
That matters for files. A file is a contiguous range of the curve. On a Z curve, the range can straddle a jump and get a long thin bounding box. On a Hilbert curve, a range stays a compact blob, so the file’s min/max box is tighter. In the table above, Hilbert reads 5 files for the box query where Z-order reads 9.
MultiDimClustering.cluster supports both curves: "zorder" maps to ZOrderClustering, and "hilbert" to HilbertClustering, which falls back to Z-order for a single column. The Hilbert variant interleaves nothing. It computes hilbert_index(numBits, rangeIds...), with numBits = 10 for 1,000 ranges. OPTIMIZE ZORDER BY uses Z-order, and liquid clustering uses Hilbert.
Q1. What does a Hilbert curve guarantee that a Z-order curve does not?
Choosing Z-order columns
- Columns that queries filter on, with stats. Usually two to four high-cardinality columns that partitioning cannot handle: ids, timestamps, coordinates.
- Few of them. With k columns, each gets 1/k of the bits at every level of the curve, so per-column locality drops as k grows. Columns that are strongly correlated (an event time and an ingestion time) add little to each other.
- Not partition columns. Delta refuses them, and Z-order runs within each partition anyway.
- Rerun as data arrives. New files are not clustered until the next run, and the next run rewrites everything.
Q1. Which are good reasons to keep the Z-order column list short? (Select all.) (select all that apply)
Try it
The lab lays out 4,096 rows into files with the code above. Each rectangle is one file’s [min, max] box, exactly what its stats would say. Orange files overlap the dashed query box and must be read. Things to try:
y BETWEEN 400 AND 450with “sorted by x”, then with Z-order and Hilbert.- “show file order” with Z-order, then Hilbert: the Z path jumps, the Hilbert path does not.
- The
y follows xdata: a linear sort is already good for both columns, because they are correlated. - 256 files: smaller files, more of them skipped, more entries in the log.
| arrival order | 64 |
| sorted by x | 11 |
| Z-order (x, y) | 9 |
| Hilbert (x, y) | 5 |
Orange boxes are files whose min/max statistics overlap the query (dashed). Grey ones are skipped from the log alone.
Summary
- Delta stores numRecords, minValues, maxValues and nullCount per file in the
addaction. Stats are collected for the first 32 columns by default, strings are truncated to 32 characters with a tie-breaker on the max, andtightBounds: falsebounds are still safe for skipping. Iceberg keeps lower and upper bounds per field id in manifests. x = vkeeps a file whenmin <= v <= max. An OR skips only if both sides can. Files without stats are always read.- Skipping depends on the layout. Random files skip nothing, a linear sort helps one column, and a space-filling curve helps several.
OPTIMIZE ZORDER BYmaps each column torange_partition_id(col, 1000), interleaves the bits, adds a noise byte, and range-partitions into total size / 1 GiB files. It rewrites every file of the partitions it touches.- Hilbert curves keep consecutive positions adjacent, which gives tighter file boxes than Z-order. Delta supports both, and liquid clustering uses Hilbert.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 11 quiz questions.