Sub topic 10
Partitioning, Z-order and liquid clustering
This chapter assumes you know basic SQL, can run commands in a Databricks notebook or SQL editor, and understand that a Delta table is a set of Parquet data files plus a transaction log. It also assumes you have seen data skipping, which is covered in the previous chapter. Here you will compare the three ways to organize data inside a table so that data skipping can prune more files.
Why layout matters for skipping
Data skipping works by comparing a query's filter against the minimum and maximum values that Delta records for each column in each file. A file can be skipped only if its range cannot contain matching rows. If every file holds a wide spread of values, every range overlaps the filter, and the query reads everything.
Clustering means placing rows with similar values in the same files. The three techniques in this chapter are different ways to achieve that.
| Technique | How you declare it | Applies to | Changeable later |
|---|---|---|---|
| Partitioning | `PARTITIONED BY` at creation | Directory layout | Only by rewriting the table |
| Z-order | `OPTIMIZE ... ZORDER BY` | Files rewritten by that run | Yes, per run |
| Liquid clustering | `CLUSTER BY` | Table property | Yes, with `ALTER TABLE` |
Partitioning
A partitioned table stores each distinct value of the partition column in its own directory. A filter on that column lets Spark skip whole directories without reading file statistics.
CREATE TABLE events_part (
event_id BIGINT,
event_date DATE,
user_id BIGINT,
payload STRING
)
PARTITIONED BY (event_date);Partitioning has sharp edges:
- High cardinality creates tiny files. Partitioning by
user_idwould produce one directory per user, each with very small files. Metadata and listing overhead then dominate. - Skew is built in. If one date holds most of the data, that partition is large while the others are small.
- It is hard to change. The partition column is fixed at creation. Choosing a different one means rewriting the table.
- It only helps one dimension. Filters on other columns get no directory pruning.
A common rule of thumb is to partition only when the table is large (multiple terabytes) and the column has low cardinality, such as a date. For most smaller tables, the other two techniques are a better choice.
Z-ordering
Z-ordering rewrites files so that rows with similar values in the chosen columns end up in the same file. It uses a space-filling curve, which maps several columns onto one ordering while keeping nearby values close together. You run it as part of OPTIMIZE.
OPTIMIZE orders;
OPTIMIZE orders ZORDER BY (customer_id);The first statement only compacts small files. The second also co-locates rows by customer_id, so a filter such as WHERE customer_id = 1042 can prune most files.
Things to know about Z-ordering:
- It is not incremental by default for the order itself. Each run rewrites the files it selects. Files that earlier runs already Z-ordered are generally not rewritten again, but new data arriving afterward is unordered until the next run.
- Effectiveness drops as you add columns. Two or three columns work reasonably, and more dilute the benefit for each one.
- The columns need statistics. By default Delta collects min/max statistics for the first 32 columns, so a Z-order column beyond that position will not benefit unless you change the setting.
- It works on top of partitioning. A common pattern is to partition by date and Z-order by another column inside each partition.
- Z-order columns cannot be partition columns.
Liquid clustering
Liquid clustering replaces both partitioning and Z-ordering for new tables. You declare clustering keys with CLUSTER BY, and OPTIMIZE organizes the data accordingly.
CREATE TABLE events (
event_id BIGINT,
event_date DATE,
user_id BIGINT,
payload STRING
)
CLUSTER BY (event_date, user_id);
OPTIMIZE events;Compared with the older techniques:
- You can change the keys.
ALTER TABLE events CLUSTER BY (user_id)changes the keys for future writes and futureOPTIMIZEruns without rewriting existing data right away. OPTIMIZEis incremental. It rewrites only files that are not yet clustered, so repeated runs are cheaper than repeated Z-ordering.- No partition directories. You avoid the tiny-file and skew problems of high-cardinality partitions.
- Keys may be high cardinality. A column like
user_idis acceptable as a key.
Limits to check in the documentation for your runtime version: the number of clustering keys is capped (currently four), clustering columns must have statistics collected, and a table cannot use both CLUSTER BY and PARTITIONED BY or ZORDER BY. Features and runtime requirements for liquid clustering change between releases, so verify them for your workspace.
The diagram shows what happens to a table over time.
Choosing between them
- New table, any size: use liquid clustering if your runtime supports it.
- Existing partitioned table that works well: leave it alone. Rewriting has a cost, and a well-chosen date partition is fine.
- Existing table with a bad partition column: migrate to liquid clustering by creating a new table with
CLUSTER BYand loading the data into it. - Runtime without liquid clustering: partition by a low-cardinality column only if the table is very large, and add
ZORDER BYfor the other filter columns.
Choose clustering keys from the columns that appear most often in WHERE clauses and join conditions. Put columns you filter on in the keys, and skip columns that are rarely filtered.
Verifying that it worked
Layout changes are only useful if queries read fewer files. After running OPTIMIZE, run the same filtered query and open the Query Profile. Compare the "files read" and "files pruned" metrics on the scan node with the values before the change. If nothing changed, check these causes:
- The filter wraps the column in a function, such as
WHERE CAST(user_id AS STRING) = '7', which defeats min/max comparison. - The column has no statistics because it sits beyond the indexed column limit.
- New data arrived after the last
OPTIMIZE. - The values you filter on are spread evenly across the whole dataset, so no layout can group them.
Summary of trade-offs
Every technique trades write or maintenance cost for read speed. Partitioning costs nothing at write time beyond file creation, but it is rigid. Z-ordering costs a rewrite on each run. Liquid clustering reduces repeated rewrite cost and keeps the keys flexible, at the price of depending on a newer runtime.
Exercise
A 200 GB table is partitioned by customer_id, which has about 5 million distinct values. Queries filter on customer_id and are slow, and the storage listing shows millions of small files. What is the problem, and what would you do instead?
Show answer
The partition column has too high a cardinality, so each partition holds a tiny amount of data and the table has millions of small files. Listing and opening them costs more than the pruning saves. Create a new table with CLUSTER BY (customer_id) (or, on runtimes without liquid clustering, an unpartitioned table with OPTIMIZE ... ZORDER BY (customer_id)), load the data into it, and run OPTIMIZE. Then confirm in the Query Profile that files read dropped.
Exercise
You have a liquid-clustered table with keys (event_date, user_id). Most queries now filter on country. How do you change the layout, and does the existing data move immediately?
Show answer
Run ALTER TABLE events CLUSTER BY (country). Existing files are not rewritten at once. The new keys apply to data written afterward and to files that later OPTIMIZE runs reorganize, so run OPTIMIZE events to cluster existing data by the new key.