Sub topic 14
Migrating an existing table to liquid clustering
This chapter assumes you have read the earlier chapters on OPTIMIZE, Z-ordering, partitioning, and the basics of liquid clustering. You should know that data skipping relies on per-file statistics and that CLUSTER BY replaces both PARTITIONED BY and ZORDER BY. Here you will learn how to move an existing table onto liquid clustering, what the move does and does not rewrite, and what can go wrong.
Which migration path applies
How you migrate depends on how the table is laid out today. Liquid clustering cannot be combined with Hive-style partitioning or with ZORDER BY on the same table. So the question is whether the table has partition columns.
| Current layout | Path | Rewrites data up front? |
|---|---|---|
| Unpartitioned Delta table, with or without past Z-ordering | `ALTER TABLE ... CLUSTER BY` | No |
| Partitioned Delta table | Create a new clustered table with `CREATE TABLE ... CLUSTER BY ... AS SELECT`, then swap names | Yes, a full copy |
| Table already liquid clustered, wrong keys | `ALTER TABLE ... CLUSTER BY` with new keys | No |
Path 1: an unpartitioned table
An unpartitioned table is the easy case. You declare the clustering columns with ALTER TABLE. This changes table metadata only. It does not move any existing rows.
ALTER TABLE events CLUSTER BY (event_date, user_id);New writes now follow the clustering definition, but files written before the ALTER keep their old layout. The existing data is clustered when you run OPTIMIZE.
OPTIMIZE events;OPTIMIZE on a clustered table is incremental. It rewrites only the files that are not yet clustered, and it skips files that already are. That means you can run it repeatedly, and each run costs roughly in proportion to the new or unclustered data.
If the table was previously Z-ordered, the old OPTIMIZE events ZORDER BY (user_id) job will fail once the table is clustered. Find and remove it from your job definitions before you migrate. Otherwise the first scheduled run after the migration will error out.
Verifying the change
DESCRIBE DETAIL shows the clustering columns and the file statistics together. Use it before and after.
DESCRIBE DETAIL events;Check these fields in the output:
clusteringColumnsshould listevent_dateanduser_id.partitionColumnsshould be empty.numFilesandsizeInByteslet you compute the average file size. DividesizeInBytesbynumFilesand compare the result before and afterOPTIMIZE.
DESCRIBE HISTORY events should also show the CLUSTER BY change as one operation, followed by an OPTIMIZE entry. The OPTIMIZE entry has metrics for files added and removed.
Path 2: a partitioned table
You cannot add CLUSTER BY to a table that has partition columns. The partitioning is part of the table definition, and the two mechanisms are mutually exclusive. The standard approach is to build a new table and switch over.
Start with the partitioned table from earlier chapters, events_partitioned. Create a clustered copy:
CREATE TABLE events_partitioned_new
CLUSTER BY (event_date, user_id)
AS SELECT * FROM events_partitioned;Then cluster the data that the CREATE TABLE ... AS SELECT wrote:
OPTIMIZE events_partitioned_new;Validate the copy before you switch anything. At a minimum, compare row counts and spot-check a few aggregates.
SELECT
(SELECT COUNT(*) FROM events_partitioned) AS old_rows,
(SELECT COUNT(*) FROM events_partitioned_new) AS new_rows;When the numbers match, swap the names. Keep the old table under a backup name until you are confident in the new one.
ALTER TABLE events_partitioned RENAME TO events_partitioned_old;
ALTER TABLE events_partitioned_new RENAME TO events_partitioned;Things the copy does not carry over
The new table is a different table, so anything attached to the old one must be recreated or checked:
- Permissions (grants) on the table.
- Table properties, such as the auto-optimize settings from the write-time optimization chapter.
- Comments, constraints, and tags.
- Views that reference the table by name. They resolve the new table after the rename, but views that were defined against the old name of a renamed table need review.
- Streaming readers. A stream reading the old table has a checkpoint tied to that table's transaction log. It cannot continue from the new table's log, so plan to restart it from a new checkpoint and decide where it should resume.
Writes during the copy
The CREATE TABLE ... AS SELECT reads a snapshot. Any rows written to the old table after that snapshot are not in the copy. For a table with continuous writers, pause the writers, or arrange to replay the gap into the new table before the swap. Skipping this step is the most common cause of silently missing rows after a migration.
Estimating the cost
The copy reads and writes the whole table. For a large table it is a one-time cost similar to a full rewrite, plus the storage for both copies until you drop the old one. Because OPTIMIZE on the new table has to cluster everything, the first run is also heavy. Size the cluster for it, and run it in a maintenance window.
Choosing the clustering columns during migration
A migration is a good moment to re-examine your keys instead of copying them from the old layout. Some guidance specific to moving from partitioning or Z-ordering:
- Partition columns are good candidates, but they do not have to carry over unchanged. A high-cardinality-friendly key such as
event_dateworks well, because clustering does not create a directory per value. - Z-order columns carry over directly. A column you used in
ZORDER BY (user_id)is usually a good clustering key. - Choose up to four columns. Put in the columns that appear most often in
WHEREclauses, and leave out columns that queries rarely filter on. - Clustering columns must have statistics collected. By default Delta collects statistics on the first 32 columns, so a key far to the right in a wide table needs a statistics setting change first.
Because keys can be changed later, you do not have to get this perfect on the first attempt.
Changing keys after migration
Changing the clustering columns is also a metadata change:
ALTER TABLE events_clustered CLUSTER BY (user_id);As before, existing files keep their old layout until OPTIMIZE runs. Be aware that OPTIMIZE skips files it already considers clustered. So after you change keys, files clustered under the old keys may not be rewritten by a plain OPTIMIZE. If you need the entire table to follow the new keys, check whether your Databricks Runtime supports OPTIMIZE ... FULL, which rewrites all records. Treat it as an expensive operation, comparable to the initial copy.
To go back to an unclustered table:
ALTER TABLE events_clustered CLUSTER BY NONE;This stops clustering for future OPTIMIZE runs. It does not undo the existing layout, and the files stay as they are.
Common errors and gotchas
| Symptom | Likely cause | Fix |
|---|---|---|
| `ALTER TABLE ... CLUSTER BY` fails on a table | The table is partitioned | Use the copy-and-swap path |
| Scheduled job fails after migration | The job still runs `OPTIMIZE ... ZORDER BY` | Replace it with plain `OPTIMIZE` |
| Queries are no faster after the `ALTER` | `OPTIMIZE` has not run, so old files are unclustered | Run `OPTIMIZE` and compare file statistics |
| Clustering has no effect on a key | No statistics on that column | Move the column into the statistics range or adjust the statistics setting |
| Row counts differ after the swap | Writers ran during the copy | Pause writers or replay the gap |
| Storage grows after migration | Old files are still present | Run `VACUUM` after the retention period |
The last row matters in both paths. OPTIMIZE rewrites files but does not delete the old ones, because time travel and concurrent readers may still need them. Run VACUUM once the retention window has passed to reclaim the space:
VACUUM events RETAIN 168 HOURS;On the swap path, dropping the backup table after your validation period frees the storage held by the old layout.
Measuring that the migration worked
Do not stop at "the command succeeded". Compare the same representative query before and after:
- Run a filter query on the clustering key, such as
WHERE user_id = 42 AND event_date >= '2024-01-01', on the old layout. Record the runtime and the files read. - Run the same query after
OPTIMIZEon the new layout. - Open the query profile for each run and compare files read against files pruned.
If the files read did not drop, the usual causes are a filter that does not match the clustering keys, missing statistics, or OPTIMIZE not having processed the data yet.
Exercise
A table named sales is partitioned by sale_date, and a nightly job runs OPTIMIZE sales ZORDER BY (customer_id). You want to move it to liquid clustering on sale_date and customer_id. What steps do you take, and what must you change in the nightly job?
Show answer
You cannot run ALTER TABLE sales CLUSTER BY because the table is partitioned. Create a new table with CREATE TABLE sales_new CLUSTER BY (sale_date, customer_id) AS SELECT * FROM sales, then run OPTIMIZE sales_new. Validate row counts, pause or replay writers so no rows are missed, recreate grants and table properties, rename the tables to swap them, and later drop the old table. Change the nightly job to plain OPTIMIZE sales, because ZORDER BY is not allowed on a clustered table.
Exercise
You ran ALTER TABLE events CLUSTER BY (user_id) on an unpartitioned table, but your user_id queries still read the same number of files. What is the most likely reason, and how do you confirm the fix?
Show answer
The ALTER only changed metadata, so the existing files are still in their old layout. Run OPTIMIZE events to cluster them, then compare the files read in the query profile and check numFiles and sizeInBytes in DESCRIBE DETAIL events.