Sub topic 7
Liquid clustering: flexible, incremental layout
This chapter assumes you know basic SQL, can run commands in a Databricks notebook or SQL warehouse, and have read the earlier chapters on OPTIMIZE, data skipping, partitioning, and Z-ordering. Liquid clustering builds on all four.
What liquid clustering is
Liquid clustering is a table layout feature for Delta tables. You declare clustering columns with CLUSTER BY, and Databricks groups rows with similar values in those columns into the same data files. Queries that filter on those columns can then skip more files, using the file-level statistics described in the data skipping chapter.
It addresses the same goal as Hive-style partitioning and Z-ordering, with three differences:
- You do not create a directory per value, so you do not get a partition explosion.
- Clustering is incremental.
OPTIMIZEworks on files that are not yet clustered and does not rewrite the whole table each time. - You can change the clustering columns later without rewriting the table up front.
Creating a liquid clustered table
Declare the clustering columns in CREATE TABLE with CLUSTER BY, where you would otherwise write PARTITIONED BY.
CREATE TABLE events_clustered (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
CLUSTER BY (event_date, user_id);
OPTIMIZE events_clustered;CLUSTER BY only records the clustering columns in the table metadata. The data is physically clustered when:
- a write operation that supports clustering on write runs, or
- you run
OPTIMIZE, which clusters data that is not yet clustered.
You can also create a clustered table from a query. This is useful when you migrate data from another table:
CREATE TABLE events_clustered_copy
CLUSTER BY (event_date, user_id)
AS SELECT * FROM events;To confirm the table is configured as you intended, run DESCRIBE DETAIL. The clusteringColumns field in the output lists the columns, and partitionColumns should be empty.
DESCRIBE DETAIL events_clustered;How incremental clustering works
Without clustering, a Delta table accumulates files in the order data arrives. Rows for any one user_id end up spread across many files, so min/max statistics cannot rule files out.
When you run OPTIMIZE on a liquid clustered table, Databricks does the following:
- It looks at the table's current clustering columns.
- It finds files that are not yet clustered, or are only partly clustered.
- It rewrites those files so rows with nearby values in the clustering columns end up in the same file.
- It leaves files that are already well clustered alone.
New writes add new unclustered files. The next OPTIMIZE run handles only that new data, plus whatever it needs to merge it into the existing layout. The cost of each run follows the amount of new data, not the table size.
Compare this with Z-ordering. OPTIMIZE ... ZORDER BY is not incremental in the same way. Z-ordering does not track which files it has already ordered, so repeated runs can rewrite data again. That is one reason liquid clustering is cheaper to maintain on tables that keep growing.
Changing clustering columns
Query patterns change. With partitioning, changing the partition column means rewriting the entire table. With liquid clustering, you alter the columns in place:
ALTER TABLE events_clustered CLUSTER BY (user_id);
ALTER TABLE events_clustered CLUSTER BY NONE;The first statement changes the clustering key to user_id. The second removes clustering.
Changing the key does not rewrite existing files immediately. New writes and later OPTIMIZE runs use the new columns. Files clustered under the old columns stay as they are until they are rewritten, so a table can briefly contain data laid out under more than one key. Skipping on the new key improves as OPTIMIZE works through the table. Databricks documents an OPTIMIZE FULL variant that reclusters all records. Use it only when you need the whole table reorganized, since it rewrites everything.
Choosing and limiting clustering columns
Pick columns that appear often in WHERE clauses and joins. Liquid clustering supports a small number of clustering columns, up to four at the time of writing, and more columns dilute the benefit for each. The next chapter covers key choice in more detail. For now, keep these rules in mind:
- Clustering columns must have statistics collected. By default, Delta collects statistics on the first 32 columns of a table, so a clustering column placed far into a wide schema may lack statistics and give no benefit.
- Unlike partitioning, high-cardinality columns such as
user_idare fine, because values are grouped into files rather than into directories. - Order of columns does not matter the way it does in a composite index. Clustering treats the columns together.
Liquid clustering compared with the alternatives
| Aspect | Partitioning | Z-ordering | Liquid clustering |
|---|---|---|---|
| Declared with | `PARTITIONED BY` | `OPTIMIZE ... ZORDER BY` | `CLUSTER BY` |
| Layout unit | Directory per value | Files within a table or partition | Files grouped by key |
| Change keys later | Requires table rewrite | Change the `ZORDER BY` list on the next run | `ALTER TABLE ... CLUSTER BY` |
| Incremental | Natural, per partition | Not tracked between runs | Yes |
| High-cardinality columns | Poor, creates many partitions | Works | Works |
| Combined with partitioning | Yes | Yes | No |
Checking that clustering worked
Run OPTIMIZE and read its output. The result reports the files removed, the files added, and size statistics. Then compare DESCRIBE DETAIL before and after:
DESCRIBE DETAIL events_clustered;
DESCRIBE HISTORY events_clustered;DESCRIBE DETAIL shows numFiles and sizeInBytes. DESCRIBE HISTORY lists each OPTIMIZE operation with its metrics. After clustering, a filtered query should read fewer files. Confirm this in the query profile, which reports files read and files pruned, instead of relying on elapsed time alone. Caching and cluster load can mask or exaggerate timing differences.
A practical test:
SELECT count(*)
FROM events_clustered
WHERE user_id = 42;Run it before and after OPTIMIZE and compare the number of files read in the query profile.
Common errors and gotchas
- Expecting
CLUSTER BYto cluster existing data immediately. AfterALTER TABLE ... CLUSTER BYon a populated table, the old files keep their old layout untilOPTIMIZEruns. - Never running
OPTIMIZE. Some writes cluster on write, but you should not rely on that alone. ScheduleOPTIMIZE, or use predictive optimization for Unity Catalog managed tables. - Mixing partitioning and clustering. Creating a table with both
PARTITIONED BYandCLUSTER BYfails. Choose one. - Using
ZORDER BYon a clustered table.OPTIMIZE ... ZORDER BYis not supported on liquid clustered tables. Change the clustering columns instead. - Clustering on a column without statistics. A column beyond the statistics limit cannot drive file skipping. Reorder the schema or adjust the statistics settings.
- Too many clustering columns. Each added column spreads the benefit thinner. Start with the one or two columns you filter on most.
- Old runtimes. Readers and writers need a Databricks Runtime that supports the feature. Older clients may be unable to read or write the table.
- Space after
OPTIMIZE. Rewriting files leaves the old ones in storage untilVACUUMremoves them, as the VACUUM chapter explains.
Exercise
A table sales is partitioned by sale_date, and analysts now mostly filter by customer_id. You want to adopt liquid clustering on a new copy of the table, clustered by customer_id. Write the statement that creates the copy, name the command that applies the clustering to the data, and explain what happens if analysts later switch to filtering by region.
Show answer
Use CREATE TABLE sales_clustered CLUSTER BY (customer_id) AS SELECT * FROM sales; with no PARTITIONED BY, then run OPTIMIZE sales_clustered; to cluster files that are not yet clustered. If analysts switch to region, run ALTER TABLE sales_clustered CLUSTER BY (region);. This changes only the metadata. New writes and later OPTIMIZE runs use region, and files clustered by customer_id are rewritten gradually rather than in one rebuild.
Exercise
Why can OPTIMIZE on a liquid clustered table be cheaper than repeated OPTIMIZE ... ZORDER BY on a Z-ordered table of the same size?
Show answer
Liquid clustering is incremental. OPTIMIZE processes files that are not yet clustered and leaves well-clustered files alone, so the work scales with new data. Z-ordering does not track which files it has already ordered, so repeated runs can rewrite data that was already organized.