Use liquid clustering for tables
Liquid clustering is a data layout optimization technique that replaces table partitioning and ZORDER. It simplifies table management and optimizes query performance by automatically organizing data based on clustering keys.
Unlike traditional partitioning, you can redefine clustering keys without rewriting existing data. This allows your data layout to evolve alongside changing analytic needs. Liquid clustering applies to both streaming tables and materialized views.
Liquid clustering is generally available for Delta Lake tables with Databricks Runtime 15.4 LTS and above, and for managed Apache Iceberg tables in Databricks Runtime 16.4 LTS and above. Databricks recommends using the latest Databricks Runtime for the best performance.
Managed Apache Iceberg v3 tables also support deletion vectors, row tracking, row-level concurrency, and automatic liquid clustering. These capabilities require Databricks Runtime 18 LTS and above. See Create and use managed tables with Apache Iceberg v3.
When to use liquid clustering
Databricks recommends liquid clustering for all new tables, including streaming tables and materialized views. The following scenarios particularly benefit from clustering:
- Queries that filter on high cardinality columns.
- Tables with heavy data skew.
- Fast growing tables that require maintenance and tuning effort.
- Tables with concurrent write requirements.
- Tables with varied or changing access patterns.
- Tables where a typical partition key might return results from too many or too few partitions.
If your queries frequently group or filter on one column, such as finding the latest date for each category, prioritize that column using Prioritize clustering keys with hierarchical clustering. Prioritizing a high-cardinality column can reduce clustering effectiveness for your other clustering keys, so review the tradeoffs before applying it.
Enable liquid clustering
You can enable liquid clustering on an existing unpartitioned table or during table creation. Clustering is not compatible with partitioning or ZORDER. Databricks recommends allowing the platform to manage all layout and optimization operations for data in your table. After enabling liquid clustering, run OPTIMIZE jobs to incrementally cluster data. See Trigger clustering.
Create tables with clustering
To enable liquid clustering, add the CLUSTER BY phrase to a table creation statement, as in the examples below. In Databricks Runtime 14.3 LTS and above, you can use DataFrame APIs and DeltaTable API in Python or Scala to enable liquid clustering for Delta Lake tables.
- SQL
- Python
- Scala
To create an empty table with clustering:
CREATE TABLE table1 (col0 INT, col1 STRING) CLUSTER BY (col0);
To create a table from existing data with clustering, CLUSTER BY must appear after the table name, not in the SELECT clause:
CREATE TABLE table2 CLUSTER BY (col0)
AS SELECT * FROM table1;
To copy a table structure including its clustering configuration:
CREATE TABLE table3 LIKE table1;
To create an empty table with clustering using the DeltaTable API:
(DeltaTable.create()
.tableName("table1")
.addColumn("col0", dataType = "INT")
.addColumn("col1", dataType = "STRING")
.clusterBy("col0")
.execute())
To create a table from an existing DataFrame:
df = spark.read.table("table1")
df.write.clusterBy("col0").saveAsTable("table2")
To create a table using the DataFrameWriterV2 API (available in Databricks Runtime 14.2 and above):
df = spark.read.table("table1")
df.writeTo("table1").using("delta").clusterBy("col0").create()
To create an empty table with clustering using the DeltaTable API:
DeltaTable.create()
.tableName("table1")
.addColumn("col0", dataType = "INT")
.addColumn("col1", dataType = "STRING")
.clusterBy("col0")
.execute()
To create a table from an existing DataFrame:
val df = spark.read.table("table1")
df.write.clusterBy("col0").saveAsTable("table2")
To create a table using the DataFrameWriterV2 API (available in Databricks Runtime 14.2 and above):
val df = spark.read.table("table1")
df.writeTo("table1").using("delta").clusterBy("col0").create()
You can specify clustering keys when creating a Delta Lake table, but not change them when appending data. To change the keys with DataFrameWriter, overwrite the entire table using saveAsTable() with overwriteSchema set to true. With DataFrameWriterV2, use replace() or createOrReplace() without setting overwriteSchema.
When overwriting with saveAsTable() without schema replacement, the table keeps its existing clustering if you omit clustering options. On a manually clustered table, passing different clustering keys without schema replacement fails with DELTA_CLUSTERING_COLUMNS_MISMATCH.
To change clustering keys on an existing table while appending data, use SQL ALTER TABLE commands to modify the clustering configuration separately from your data write operations. See Change clustering keys.
In Databricks Runtime 16.4 LTS and above, you can create tables with liquid clustering enabled using Structured Streaming writes, as in the following examples:
- SQL
- Python
- Scala
CREATE TABLE table1 (
col0 STRING,
col1 DATE,
col2 BIGINT
)
CLUSTER BY (col0, col1);
(spark.readStream.table("source_table")
.writeStream
.clusterBy("column_name")
.option("checkpointLocation", checkpointPath)
.toTable("target_table")
)
spark.readStream.table("source_table")
.writeStream
.clusterBy("column_name")
.option("checkpointLocation", checkpointPath)
.toTable("target_table")
Delta Lake tables with liquid clustering enabled use Delta writer version 7 and reader version 3. Delta clients that don't support these protocols cannot read these tables. You can't downgrade table protocol versions. See Delta Lake feature compatibility and protocols.
To override default feature enablement, such as deletion vectors, see Override default feature enablement (optional).
Enable on existing tables
To enable liquid clustering on an existing unpartitioned Delta Lake table, do the following:
ALTER TABLE <table_name>
CLUSTER BY (<clustering_columns>)
For managed Apache Iceberg tables, consider the following:
- For tables with the v2 spec, you must explicitly turn off deletion vectors and row tracking when enabling liquid clustering on an existing table.
- For tables with the v3 spec, turning off these features is not required because deletion vectors and row tracking are supported. See Create and use managed tables with Apache Iceberg v3.
The default behavior does not apply clustering to previously written data. To force reclustering, use OPTIMIZE <table_name> FULL or OPTIMIZE <table_name> FULL WHERE <predicate>. See Force reclustering.
Convert a partitioned table to liquid clustering
In Databricks Runtime 18.1 and above, to convert an existing partitioned Delta Lake table to liquid clustering, use REPLACE PARTITIONED BY WITH CLUSTER BY in an ALTER TABLE statement. Conversion minimizes reader and writer downtime and supports both external and managed tables. Managed Apache Iceberg tables don't need conversion, because they use partition definitions as liquid clustering keys. See Convert a partitioned table to liquid clustering.
Remove clustering keys
To remove clustering keys, use the following syntax:
ALTER TABLE table_name CLUSTER BY NONE;
Choose clustering keys
Choose clustering keys based on the columns most commonly used in query filters. The right keys significantly improve data skipping and query performance.
Let Databricks choose clustering keys
Databricks recommends using automatic liquid clustering, which selects clustering keys based on the table's query workload. Automatic liquid clustering requires predictive optimization. See Use automatic liquid clustering.
Select clustering keys and optimize on demand
This feature is in Beta. To use it, a workspace admin must turn on OPTIMIZE EXTENDED from the Previews page. See Manage Databricks previews.
Run representative queries and then use OPTIMIZE table_name EXTENDED to select keys and cluster a table with automatic liquid clustering for a proof of concept or benchmark. On other tables, the command returns a clustering recommendation without changing the keys. See Optimize table layout with OPTIMIZE EXTENDED for the walkthrough and example outputs.
Key selection guidelines
When you manually specify clustering keys, choose columns based on the columns most frequently used in query filters. You can define clustering keys in any order. If two columns are highly correlated, you only need to include one of them as a clustering key.
To prioritize clustering on some columns before others, use hierarchical clustering.
You can specify up to four clustering keys. For smaller tables (less than 10 TB), using more clustering keys can degrade performance when filtering on a single column. For example, filtering with four keys performs worse than filtering with two keys. However, as table size increases, this performance difference becomes negligible for single-column queries.
Clustering keys must be columns that have statistics collected. By default, Delta Lake tables collect statistics for the first 32 columns. See Specify statistics columns.
Supported data types
Clustering supports these data types for clustering keys:
- Date
- Timestamp
- TimestampNTZ (Databricks Runtime 14.3 LTS and above)
- String
- Integer, Long, Short, Byte
- Float, Double, Decimal
You can cluster by a StructField using dot notation, such as CLUSTER BY (struct_col.field). Nested struct fields are supported to any depth, such as CLUSTER BY (struct_col.nested.field). The field's data type must be one of the supported types in the preceding list.
You can't cluster by any of the following:
- Complex types, such as
StructType,MapType, orArrayType MapTypeandArrayTypeelements, such asmap_col['key'],array_col[0], ormap_col.key.
Choose keys when you migrate from partitioning or Z-order
Databricks recommends that you convert partitioned tables with the REPLACE PARTITIONED BY WITH CLUSTER BY command. See Convert a partitioned table to liquid clustering.
If you're converting an existing table, consider the following recommendations:
Current data optimization technique | Recommendation for clustering keys |
|---|---|
Hive-style partitioning | Use partition columns as clustering keys. |
Z-order indexing | Use the |
Hive-style partitioning and Z-order | Use both partition columns and |
Generated columns to reduce cardinality (for example, date for a timestamp) | Use the original column as a clustering key, and don't create a generated column. |
Prioritize clustering keys with hierarchical clustering
Available in Databricks Runtime 17.1 and above, use hierarchical clustering with OPTIMIZE to improve data skipping by prioritizing some clustering keys over others. For example, if you previously partitioned a table by event_date and used ZORDER on customer_id, prioritize event_date and set customer_id as a standard clustering key.
How hierarchical clustering works
Hierarchical clustering organizes data by the highest-priority column first, then by each subsequent column in the order you specify. Any remaining clustering keys are standard clustering keys. When you set hierarchical clustering manually, predictive optimization respects the configuration and does not override it.
To configure hierarchical clustering, set the delta.liquid.hierarchicalClusteringColumns table property. Every column in the property must also be a clustering key. The order of columns in the property matters: the first column has the highest priority.
Hierarchical clustering might improve data skipping for queries that frequently filter on the prioritized columns. Specify columns with low cardinality to maximize data skipping. For multiple hierarchical clustering keys, order them from lower cardinality to higher cardinality.
Databricks recommends keeping high-cardinality columns as standard clustering keys rather than hierarchical clustering keys. High-cardinality hierarchical clustering keys can reduce clustering effectiveness for lower-priority clustering keys and reduce query performance.
Create a table
The following example creates a table with four clustering keys. Hierarchical clustering first organizes data by event_date, and then by store_id. The customer_id and product_id columns are standard clustering keys.
CREATE TABLE events (
event_date DATE,
store_id BIGINT,
customer_id BIGINT,
product_id BIGINT
)
CLUSTER BY (event_date, store_id, customer_id, product_id)
TBLPROPERTIES (
'delta.liquid.hierarchicalClusteringColumns' = 'event_date,store_id'
);
After you write data to the table, OPTIMIZE clusters the new data using the specified hierarchy. See Trigger clustering.
Configure an existing table
On an existing clustered table, use ALTER TABLE, and then run OPTIMIZE FULL to recluster all existing data using the specified hierarchy:
ALTER TABLE events SET TBLPROPERTIES (
'delta.liquid.hierarchicalClusteringColumns' = 'event_date,store_id'
);
OPTIMIZE events FULL;
Set hierarchical clustering keys during conversion
When you convert a partitioned table to liquid clustering, partition columns that you keep as clustering keys become hierarchical clustering keys. For example, if a table is partitioned by (p1, p2), the following command converts the table to liquid clustering and uses p1 and p2 as hierarchical clustering keys and c1 and c2 as standard clustering keys:
ALTER TABLE table_name
REPLACE PARTITIONED BY WITH CLUSTER BY (p1, p2, c1, c2);
You don't need to set the delta.liquid.hierarchicalClusteringColumns table property after conversion.
Revert to standard clustering
To revert to standard clustering, unset the table property:
ALTER TABLE events UNSET TBLPROPERTIES (
'delta.liquid.hierarchicalClusteringColumns'
);
Write data to a clustered table
To write to a clustered Delta Lake table, you must use a Delta writer client that supports all Delta write protocol table features used by liquid clustering. To write to a clustered Iceberg table, you can use Unity Catalog's Iceberg REST Catalog API. On Databricks, you must use Databricks Runtime 13.3 LTS and above.
Operations that support clustering on write
Operations that cluster on write include the following:
INSERT INTOoperationsCTASandRTASstatementsCOPY INTOfrom Parquet formatspark.write.mode("append")
Size thresholds for clustering
Clustering on write only triggers when data in the transaction meets a size threshold. These thresholds vary by the number of clustering columns and are lower for Unity Catalog managed tables than other Delta Lake tables.
Number of clustering columns | Threshold size for Unity Catalog managed tables | Threshold size for other Delta Lake tables |
|---|---|---|
1 | 64 MB | 256 MB |
2 | 256 MB | 1 GB |
3 | 512 MB | 2 GB |
4 | 1 GB | 4 GB |
Because not all operations apply liquid clustering, Databricks recommends frequently running OPTIMIZE to ensure that all data is efficiently clustered.
Cluster streaming writes
Structured Streaming workloads support clustering on write when you set the Spark config spark.databricks.delta.liquid.eagerClustering.streaming.enabled to true. Clustering for these workloads only triggers if at least one of the last five streaming updates exceeds a size threshold from the table above.
Trigger clustering
Predictive optimization automatically runs OPTIMIZE commands for enabled tables. See Predictive optimization for Unity Catalog managed tables. When using Predictive optimization, Databricks recommends disabling any scheduled OPTIMIZE jobs.
To trigger clustering, you must use Databricks Runtime 13.3 LTS or above. Databricks recommends Databricks Runtime 17.3 LTS and above for faster OPTIMIZE performance on large tables. Use the OPTIMIZE command on your table:
OPTIMIZE table_name;
Liquid clustering is incremental, meaning that OPTIMIZE only rewrites data as necessary to accommodate data that needs clustering. OPTIMIZE does not rewrite data files with clustering keys that don't match the data being clustered. See Force reclustering.
If you aren't using predictive optimization, Databricks recommends scheduling regular OPTIMIZE jobs to cluster data. For tables experiencing many updates or inserts, Databricks recommends scheduling an OPTIMIZE job every one or two hours. Because liquid clustering is incremental, most OPTIMIZE jobs for clustered tables run quickly.
Force reclustering
In Databricks Runtime 16.0 and above, you can force reclustering of existing records in a table with the following syntax:
OPTIMIZE table_name FULL;
Running OPTIMIZE <table_name> FULL reclusters all existing data as necessary. For large tables that have not previously been clustered on the specified keys, this operation might take hours.
Run OPTIMIZE <table_name> FULL when you enable clustering for the first time or change clustering keys. OPTIMIZE <table_name> FULL may rewrite files that are not clustered or that were clustered with different clustering keys. It does not rewrite files that are already clustered with the current clustering keys, no matter which operation clustered them. For example, files clustered by an earlier OPTIMIZE run or by predictive optimization are not rewritten.
If the clustering keys have not changed since the data was clustered, OPTIMIZE <table_name> FULL runs the same as OPTIMIZE. In this scenario, OPTIMIZE uses an incremental approach and only rewrites files that are not clustered.
Recluster a subset of records
In Databricks Runtime 18.1 and above, you can force reclustering for a subset of records using OPTIMIZE <table_name> FULL WHERE <predicate>. A file is included if any part of its range overlaps with the predicate. As with OPTIMIZE <table_name> FULL, included files that are already clustered with the current clustering keys are not rewritten. See Parameters.
OPTIMIZE events FULL WHERE event_date >= '2025-01-01';
Managed Apache Iceberg tables that use liquid clustering also support OPTIMIZE <table_name> FULL and OPTIMIZE <table_name> FULL WHERE <predicate>. See Optimize managed Iceberg tables.
Read data from a clustered table
You can read data in a clustered Delta Lake table using any Delta Lake client that supports reading deletion vectors. Using the Iceberg REST Catalog API, you can read data in a clustered Iceberg table. Liquid clustering improves query performance through automatic data skipping when filtering on clustering keys.
SELECT * FROM table_name WHERE cluster_key_column_name = "some_value";
Manage clustering keys
See how a table is clustered
You can use DESCRIBE commands to see the clustering keys for a table, as in the following examples:
DESCRIBE TABLE table_name;
DESCRIBE DETAIL table_name;
Change clustering keys
You can change clustering keys for a table at any time by running an ALTER TABLE command, as in the following example:
ALTER TABLE table_name CLUSTER BY (new_column1, new_column2);
When you change clustering keys, subsequent OPTIMIZE and write operations use the new clustering approach, but existing data is not rewritten. To rewrite existing data with the updated clustering keys, see Force reclustering.
You can also turn off clustering by setting the keys to NONE, as in the following example:
ALTER TABLE table_name CLUSTER BY NONE;
Setting cluster keys to NONE does not rewrite clustered data, but prevents future OPTIMIZE operations from using clustering keys.
Use liquid clustering from an external engine
You can enable liquid clustering on managed Iceberg tables from external Iceberg engines. To enable liquid clustering, specify partition columns when creating a table. Unity Catalog interprets the partitions as clustering keys. For example, run the command below in OSS Spark:
CREATE OR REPLACE TABLE main.schema.icebergTable
PARTITIONED BY c1;
To turn off liquid clustering:
ALTER TABLE main.schema.icebergTable DROP PARTITION FIELD c2;
To change clustering keys using Iceberg partition evolution:
ALTER TABLE main.schema.icebergTable ADD PARTITION FIELD c2;
If you specify a partition using a bucket transform, Unity Catalog drops the expression and uses the column as a clustering key:
CREATE OR REPLACE TABLE main.schema.icebergTable
PARTITIONED BY (bucket(c1, 10));
Compatibility for tables with liquid clustering
Liquid clustering uses Delta Lake table features that require specific Databricks Runtime versions for reading and writing. Tables created with liquid clustering in Databricks Runtime 14.3 LTS and above use checkpoint V2 by default. You can read and write tables with checkpoint V2 in Databricks Runtime 13.3 LTS and above. See Checkpoint V2.
To support readers using Databricks Runtime 12.2 LTS to 13.2, disable checkpoint V2 and downgrade the table protocol. See Downgrade to classic.
Override default feature enablement (optional)
You can override default Delta Lake table feature enablement during liquid clustering enablement. This prevents upgrades of the reader and writer protocols associated with those table features. You must have an existing table to complete the following steps:
-
Use
ALTER TABLEto set the table property that turns off one or more features. For example, to turn off deletion vectors run the following:SQLALTER TABLE table_name SET TBLPROPERTIES ('delta.enableDeletionVectors' = false); -
Enable liquid clustering on the table by running the following:
SQLALTER TABLE <table_name>CLUSTER BY (<clustering_columns>)
The following table has information on the Delta features you can override and how enablement affects compatibility with Databricks Runtime versions:
Delta feature | Runtime compatibility | Property to override enablement | Effects on liquid clustering if turned off |
|---|---|---|---|
Deletion vectors | Reads and writes require Databricks Runtime 12.2 LTS and above. |
| Turning off deletion vectors also turns off row-level concurrency, making transactions and clustering operations more likely to conflict. See Row-level concurrency.
|
Row tracking | Writes require Databricks Runtime 13.3 LTS and above. Can be read from any Databricks Runtime version. |
| Turning off row tracking also turns off row-level concurrency, making transactions and clustering operations more likely to conflict. See Row-level concurrency. |
Checkpoint V2 | Reads and writes require Databricks Runtime 13.3 LTS and above. |
| No effect on liquid clustering behavior. See Checkpoint V2. |
Limitations
- Databricks Runtime 15.1 and below: Clustering on write does not support source queries that include filters, joins, or aggregations.
- Databricks Runtime 15.4 LTS and below: You cannot create a table with liquid clustering enabled using a Structured Streaming write. You can use Structured Streaming to write data to an existing table with liquid clustering enabled.
- Apache Iceberg v2: Row-level concurrency isn't supported on managed Apache Iceberg v2 tables because deletion vectors and row tracking aren't supported.
- Row-level concurrency is supported on managed Apache Iceberg v3 tables because the v3 spec supports deletion vectors and row tracking. See Create and use managed tables with Apache Iceberg v3.