Sub topic 8
Choosing clustering and Z-order columns
This chapter assumes you can read basic SQL and know how OPTIMIZE compacts files. It also assumes you know that Delta keeps min/max statistics per data file. Here you will learn how to pick the columns for OPTIMIZE ... ZORDER BY and CLUSTER BY, and how to check that the choice works.
What the column choice controls
Both Z-ordering and liquid clustering rearrange rows so that similar values of the chosen columns land in the same files. A query that filters on those columns can then use each file's min/max statistics to skip files that cannot match. The columns you choose decide which queries get that benefit.
Pruning can only happen when two conditions hold:
- Queries filter on the column, so the engine has a predicate to compare against the statistics.
- The file statistics for that column exist and are narrow, meaning each file covers a small range of values.
Column choice is mostly about satisfying both conditions for the queries that matter most.
Start from the query workload
Look at how the table is actually read before you look at its schema. Good candidates are:
- Columns that appear in
WHEREclauses of frequent or expensive queries. - Columns used in selective range filters, such as timestamps and dates.
- Columns used for point lookups, such as
user_idororder_id. - Join keys, when the join is followed by a selective filter or when you want to reduce scanned data on the large side.
Poor candidates are columns that never appear in filters, columns with a single value, and columns that only appear inside functions that block statistics use. A filter like WHERE lower(country) = 'de' compares the function result and not the raw value, so file min/max statistics on country may not help. A filter like WHERE event_date >= '2024-01-01' compares the raw column and is a good fit.
You can find real filter patterns in the query history of your SQL warehouse, in the Spark UI for jobs, or by asking the people who own the dashboards. Rank the filters by how often the query runs and how much data it scans. A rare query that scans the whole table matters less than a dashboard query that runs every minute.
Cardinality
Cardinality is the number of distinct values in a column. It affects partitioning and clustering in opposite ways.
| Cardinality | Example | Partitioning | Z-order or clustering |
|---|---|---|---|
| Low (tens of values) | `country`, `status` | Possible, but only if every partition stays large | Works, but few distinct values means limited pruning gain beyond partitioning |
| Medium (thousands) | `event_date` over years | Often acceptable for dates | Works well |
| High (millions) | `user_id`, `order_id` | Creates far too many partitions and small files | Works well, and is the main use case |
High-cardinality columns are the reason these techniques exist. Partitioning on user_id would create one directory per user. Z-ordering or clustering on user_id instead keeps related values together inside a manageable number of files.
Very low-cardinality columns are less useful as the only key. If status has three values and each value appears in every file after compaction, nothing can be skipped. Clustering on it is still sometimes worthwhile when the values are skewed, for example when you filter for a rare status.
Watch out for one case: a column whose values are nearly unique and random, such as a UUID. Rows with similar UUIDs are not related to anything a query would filter on by range. Equality lookups on a UUID still benefit, because each file holds a narrow range of values.
Statistics must exist for the column
Data skipping uses file-level statistics. By default Delta collects min/max and null counts for the first 32 columns of the table schema. A column outside that set has no statistics, so Z-ordering or clustering on it cannot produce file skipping.
Two practical consequences follow:
- Put columns you filter on near the front of the schema when you create the table.
- Do not put long free-text columns, such as
payload, early in the schema. Statistics on long strings are truncated and are not useful for filtering.
You can check the current setting and change it with a table property:
SHOW TBLPROPERTIES events;
ALTER TABLE events SET TBLPROPERTIES (
'delta.dataSkippingNumIndexedCols' = '8'
);The new setting applies to statistics written from then on. Files written earlier keep the statistics they already have, so rewrite them (for example with OPTIMIZE) or recompute statistics, as described in the Databricks documentation, before judging the result. On Databricks you can also name specific columns with the delta.dataSkippingStatsColumns property. Lowering the number of indexed columns can also make writes cheaper on very wide tables.
For liquid clustering, Databricks requires clustering columns to have statistics collected. Choose columns inside the indexed set.
How many columns, and in what order
Both techniques interleave the values of the chosen columns, so adding columns dilutes the benefit for each one. With one column, files are tightly grouped on that column. With two, files are moderately grouped on each. With many, the grouping on any single column gets loose and pruning drops.
Guidelines:
- Use one to three columns in most cases. Liquid clustering allows at most four.
- Pick columns that are filtered together or separately in the key queries. Filtering on any subset of the chosen columns can still prune, though the more selective the combination, the better.
- Column order does not matter. Unlike sorting, Z-order and liquid clustering treat the columns symmetrically, so
CLUSTER BY (event_date, user_id)andCLUSTER BY (user_id, event_date)behave alike. - Z-order columns cannot be partition columns of the same table. A column you partition by already has its values separated by directory, so Z-ordering it adds nothing.
Applying the choice
For a Z-ordered table, you name the columns each time you run OPTIMIZE:
OPTIMIZE events_partitioned
WHERE event_date >= '2024-01-01'
ZORDER BY (user_id);For a liquid clustered table, you declare the columns once on the table:
CREATE TABLE events_clustered (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
CLUSTER BY (event_date, user_id);If the workload changes, you can change the keys without rewriting the table up front:
ALTER TABLE events_clustered CLUSTER BY (user_id);The new keys apply to data processed by later OPTIMIZE runs. Files already clustered under the old keys are not necessarily rewritten right away, so expect a period where the table holds a mix of layouts. This is one of the practical advantages over Z-ordering, where changing the column list means the next OPTIMIZE has to redo the work on data that was already Z-ordered.
The Python API takes the column names as arguments:
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events")
dt.optimize().executeZOrderBy("user_id", "event_date")Databricks also offers automatic key selection for Unity Catalog managed tables (CLUSTER BY AUTO), where the platform chooses and changes keys from observed query patterns. It needs predictive optimization to be enabled. Check the current documentation for availability in your workspace before relying on it.
Common mistakes
- Choosing by schema, not by queries. A column named
idis not a good key if every query filters onevent_date. - Keys with no statistics. The
OPTIMIZEcommand succeeds, but queries skip no more files than before. - Too many keys. Eight Z-order columns give weak pruning on all of them.
- Z-ordering a partition column. It adds nothing, and Delta rejects it.
- Judging success by query time alone. Caching, cluster size, and warm-up distort timings. Compare files scanned or bytes read instead.
Verify the choice
After optimizing, run a representative query and open its query profile or Spark UI. Compare "files read" or "files pruned" against the total file count from DESCRIBE DETAIL events. A good key choice shows a large share of files pruned for the target filter. If the number of files read barely changed, check three things in order: whether statistics exist for the column, whether the filter uses the raw column, and whether OPTIMIZE has actually run on the data you are querying.
Exercise
A table orders has columns order_id (unique), customer_id (about 2 million values), status (4 values), order_ts (timestamp), and notes (long text). The two main queries are "all orders for one customer in the last 30 days" and "one order by order_id". You are creating it with liquid clustering. Which columns would you choose, and what should you check about the schema?
Show answer
Cluster by customer_id and order_ts, and consider adding order_id only if point lookups on it are frequent, so at most three keys. Leave out status (low cardinality, not used in the main filters) and notes (not filtered on, and long-string statistics are not useful). Check that the chosen columns are within the first 32 columns, or the configured indexed set, so file statistics exist, and place notes late in the schema. After running OPTIMIZE, confirm with the query profile that the two queries read only a small share of the files.