Sub topic 2
Partitioning, Z-Ordering, and Liquid Clustering
This chapter assumes basic SQL, Delta tables, Parquet files, and Spark partitions.
Partitioning and when it helps or hurts
Partitioning stores files in directory-like groups based on one or more columns. A query that filters on a partition column can skip unrelated groups before reading files.
CREATE TABLE events (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
PARTITIONED BY (event_date);Partition only on columns that:
- Appear often in filters.
- Have relatively few distinct values.
- Produce enough data in each partition.
A date column can work well for a large event table. A unique user_id usually creates too many small partitions. Small partitions increase file-management overhead and can make writes and reads slower.
Co-locating data with Z-ordering
Z-ordering rewrites files so rows with similar values are stored together across selected columns. Delta Lake records file-level statistics, such as minimum and maximum values. These statistics let the engine skip files that cannot match a filter.
OPTIMIZE events
WHERE event_date >= '2024-01-01'
ZORDER BY (user_id);Use Z-ordering for columns that are frequent filter conditions but are unsuitable as partition columns. Too many Z-order columns can reduce the benefit because the layout must serve several access patterns.
Liquid clustering: flexible, incremental layout
Liquid clustering is an alternative to fixed partitioning. You declare clustering columns with CLUSTER BY, then OPTIMIZE arranges data using those columns.
CREATE TABLE events_clustered (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
CLUSTER BY (event_date, user_id);
OPTIMIZE events_clustered;You can change the clustering keys without immediately rewriting the entire table:
ALTER TABLE events_clustered CLUSTER BY (user_id);Liquid clustering suits tables whose query patterns change or whose data does not fit stable partitions.
Choosing columns
Choose columns from actual query filters, not from column names alone. Prefer columns that eliminate many files and have enough repeated values. Check whether the table is read mostly by date, user, region, or another predictable key.
| Strategy | Best fit | Main risk |
|---|---|---|
| Partitioning | Stable, low-cardinality filters | Too many small partitions |
| Z-ordering | Frequent filters within existing partitions | Rewrite cost and too many keys |
| Liquid clustering | Changing or multidimensional access patterns | Requires supported Delta features |
Exercise
A table is often filtered by user_id, which has millions of values. Should you partition by user_id?
Show answer
No. Use Z-ordering or liquid clustering, depending on whether the access pattern is stable.