Delta Liquid Clustering vs. Hive Partitioning and Z-Order
A query asks for one customer’s purchases. Your table contains purchases from millions of customers. Why should the query read files that cannot contain the answer?
That question connects Hive-style partitioning, Z-Ordering, and Delta liquid clustering. All three influence physical data layout so an engine can avoid unnecessary reads. They do not make a query faster simply by being enabled: the layout must match useful filters, the engine must exploit it, and the maintenance cost must be worthwhile.
Liquid clustering declares clustering columns as part of a Delta table’s metadata and uses maintenance operations to organize related records into files. Its useful distinction is flexibility: you can change the desired clustering keys without immediately rewriting existing data.
The key caveat: changing the keys does not reorganize old files. The key-change example separates policy changes from historical reclustering.
The core comparison covers open-source Delta Lake, meaning the original project rather than a platform’s managed implementation. It uses the Delta Lake clustering documentation and versioned sources. The single practical walkthrough uses Microsoft Fabric Runtime 2.0: Spark 4.1 and Delta Lake 4.2, supplied as a managed service. Fabric-specific settings and diagnostics are labeled separately; they are not promises about every Delta Lake deployment.
Choose your learning path
- Level 1 - Understand the concepts: start with files and skipping and the three technique introductions, then read the comparison and workload recommendations. You can leave the internal mechanics and operational details for a second pass.
- Level 2 - Understand runtime mechanics: explore how records become clustered files, how maintenance tracks completed work, and what changing keys really does. The Fabric Runtime 2.0 section explains its incremental strategy and defaults.
- Level 3 - Apply and validate: follow the SQL lab, choosing its functional or diagnostic route. The measurement plan and advanced migration runbook support deeper evaluation; completing the small functional lab alone does not establish production readiness.
First, understand files and skipping
Four layers, four different jobs
| Layer | Job in this article | Archive analogy |
|---|---|---|
| Apache Spark | Executes SQL, reads data, and runs optimization work | The workers retrieving or reorganizing records |
| Delta Lake | Defines the table’s transactional state through its log, including active files and metadata | The authoritative inventory of which boxes belong to the archive |
| Apache Parquet | Stores the table’s columnar data in files | The boxes holding records |
| Microsoft Fabric | Hosts the managed Spark/Delta environment and lakehouse storage integration used in the lab | The facility where this particular archive operates |
A logical table is the rows you query. Its physical layout is how those rows are spread across files. The same logical answer can come from several physical layouts. The analogy is only a memory aid: Delta uses a transaction log, not a manually maintained inventory.
The SQL snippets before the lab are independent illustrations, not cells to execute in sequence. Start creating tables only in the numbered walkthrough; it uses separate, explicitly qualified names to avoid collisions.
One running sales example
Imagine a hypothetical sales table with a billion transactions in 10,000 Parquet data files:
| Column | Meaning |
|---|---|
transaction_id |
One purchase |
customer_id |
The customer who made it |
region |
Sales region |
product_id |
The purchased product |
transaction_date |
Purchase date |
amount |
Purchase amount |
These are illustrative scale numbers, not a benchmark. The query might be:
SELECT SUM(amount)
FROM sales
WHERE customer_id = 42;
If that customer’s rows are scattered throughout the table, many files may remain candidates for reading. A more useful layout can concentrate those rows into fewer files.
A predicate is a condition such as customer_id = 42. A selective predicate returns a small fraction of the table: for example, 20 purchases out of a million. Here, “highly selective” means few matches, not many. Compaction combines small files to reduce overhead; it does not by itself guarantee that customer values become neatly grouped.
Think of the table as an archive of boxes:
- Partitioning puts boxes in labeled rooms, such as one room per region.
- Z-Ordering reorganizes records within the relevant collection of boxes to improve locality across selected dimensions.
- Liquid clustering records the desired organization policy and tracks clustering work so maintenance can incrementally improve the layout.
The analogy stops at the physical storage model. Delta readers consult the transaction log to identify the table’s active files; they do not have to discover the table by blindly walking every directory. A partition directory is also not a Spark execution partition, which is a unit of distributed processing.
Partition pruning and data skipping are related, not identical
Partition pruning excludes files using partition values, such as region = 'US'.
Data skipping excludes files using available statistics, such as a minimum and maximum customer_id. If a file’s IDs range from 200 to 500, it cannot contain customer 100. If its range is 1 to 10,000, it might contain customer 100, even when it actually does not.
The statistics help prove a file cannot match. They are not an exact list of every value and are not a traditional lookup index. Rows still need filtering inside files that remain candidates. Readers may also perform finer-grained Parquet optimizations; the examples here focus on Delta file selection.
Delta records these per-file statistics in its transaction log, alongside metadata identifying active files. Statistics are not necessarily collected for every column: the documented default covers the first 32 columns, with coverage affected by settings and supported types. A better physical layout cannot provide min/max-based skipping on a column whose relevant statistics are missing. See the Fabric file-skipping guide for coverage settings.
The same principle underlies both Z-Order and liquid clustering: useful locality makes skipping more effective. The difference is not that one has statistics and the other does not. See the Delta Lake optimization guide for file statistics and Z-Ordering.
Hive-style partitioning: give values separate rooms
Hive-style partitioning groups rows by the exact values of partition columns, usually reflected in paths such as region=US/. The relevant table-definition clause is shown below as a fragment; the lab supplies the complete CREATE TABLE.
PARTITIONED BY (region)
A simplified layout is:
sales_partitioned/
_delta_log/
region=US/
part-....parquet
region=UK/
part-....parquet
region=IN/
part-....parquet
For WHERE region = 'US', partition metadata can eliminate the other regions. For WHERE customer_id = 42 without a region condition, region partitioning alone cannot identify the correct room.
Why cardinality and skew matter
Cardinality means the number of distinct values. Three regions have low cardinality; ten million customer IDs have high cardinality.
Partitioning by customer ID can scatter data across a huge number of small partitions. Frequent small writes can worsen the small-file problem, increasing file-management and query-planning work relative to useful data processing.
Skew means an uneven distribution. If one region holds 80% of the data, partitioning by region does not make the regions equally sized or eliminate a hot region. Adding machines does not change that layout decision.
The Delta best-practices guide recommends avoiding very high-cardinality partition columns and gives roughly 1 GB per partition as a rule of thumb. That is a starting heuristic, not a correctness requirement or a universal performance boundary.
When partitioning remains a good choice
Keep it in the conversation when queries consistently filter on stable, bounded keys, each populated partition has substantial data, or established workflows depend on explicit partition boundaries.
Date partitioning is a familiar example, but “always partition by date” is not a design method. Daily partitions can be sensible for a large event feed and wasteful for a small table.
Changing the partition scheme normally requires rewriting into a new physical layout. Use supported table operations, not manual directory moves or deletion.
Z-Order: improve locality across selected dimensions
Z-Ordering rearranges records to bring related values closer together across one or more columns:
OPTIMIZE sales_zordered
ZORDER BY (customer_id, product_id);
sales_zordered is an illustrative name for a non-liquid table. Its counterpart in the lab is dbo.delta_layout_zordered.
For intuition, start with a single customer dimension. Mixed files may each span customers 1 through 10,000. A reorganized layout might have narrower, less-overlapping ranges, letting an equality filter reject more files.
With multiple dimensions, a Z-order curve maps multidimensional proximity into an ordering used to organize data. It is not simply ORDER BY customer_id, product_id, and it does not guarantee one file per customer or perfectly disjoint min/max ranges.
The listed columns do not have SQL’s conventional lexicographic first-column priority: do not read ZORDER BY (customer_id, product_id) as “finish sorting every customer before considering product.” Choose the dimensions for useful filters, not to mimic an ORDER BY prefix. This does not promise that reversing the columns produces identical physical files.
Picture customer ID on a horizontal axis and product ID on a vertical axis. Each purchase is a point. A space-filling curve gives nearby points an approximate one-dimensional traversal order, so groups written into files can retain useful locality on both axes. Z-order and Hilbert curves are different ways to construct such an order; neither can preserve every neighbor relationship perfectly.
Partitioning and Z-Order can work together
A region-partitioned table can also be Z-Ordered within selected partitions:
OPTIMIZE sales_partitioned
WHERE region = 'US'
ZORDER BY (customer_id, product_id);
Here, the WHERE condition scopes maintenance using a partition column. It is not a general row filter for arbitrary nonpartition columns.
That combination is a useful distinction: partitioning and Z-Order are not mutually exclusive. Delta Lake liquid clustering, on the other hand, cannot be combined with Hive-style partitioning or Z-Order on the same table.
The maintenance trade-off
- Appending records does not mean they are automatically Z-Ordered.
- Changing the columns in a later
ZORDER BYis possible; achieving that organization over historical data requires rewriting relevant files. - More dimensions spread the locality benefit. Choose commonly filtered, selective columns rather than every available column.
- Statistics must exist on the relevant columns for data skipping to exploit the layout.
Do not assume each invocation rewrites the entire table. Equally, do not budget a Z-Order run as if it were metadata-only or equivalent to liquid’s tracked incremental clustering. Scope, file selection, incoming data, and implementation behavior determine the actual work.
Liquid clustering: declare a policy, then maintain the layout
Liquid clustering makes selected keys part of the table definition. This is the corresponding clause fragment, not a complete statement:
CLUSTER BY (customer_id, product_id)
It does not create one exact-value directory per customer or product. The engine can organize useful groups across files without committing to Hive-style directory partitions.
Then run:
OPTIMIZE sales_liquid;
This is the physical work: eligible data is reorganized according to the clustering policy. Declaring the keys is not proof that every append immediately produces fully clustered data, nor does the OSS declaration provision a background maintenance scheduler.
Why not just keep using Z-Order? Both aim to improve locality for file skipping. With ZORDER BY, each maintenance command specifies the dimensions; liquid clustering persists that policy and tracks completed clustering work for subsequent maintenance. The distinction is the table’s organization and maintenance model, not simply a different curve.
How the records become clustered files
For the Fabric Runtime 2.0 implementation used in this article’s lab, the documented process is:
- Select eligible files, rather than assuming every active file needs rewriting.
- Group the work into bins targeting useful output file sizes.
- Organize the selected records by the clustering dimensions. Fabric documents a Hilbert curve for multiple columns and Z-Order for a single column; the goal is useful locality, not ordinary lexicographic sorting.
- Write replacement files and record file replacements and clustering metadata in the Delta log.
- Use the resulting file statistics during queries to reject files that cannot match a filter.
For our customer/product example, purchases nearby in that two-dimensional space can end up together, making file ranges more useful for skipping. Figure 2 illustrates that intuition, not exact file boundaries. Liquid clustering is the layout-management feature; it is not another name for the Hilbert algorithm, nor a guarantee that every implementation uses the same curve.
What makes the maintenance incremental?
The open-source Delta Lake implementation tracks clustering information, including ZCube metadata, to distinguish clustering work already performed from data that needs attention. You can think of a ZCube as a tracked group of files produced by clustering work, not a new Hive partition or a traditional database index.
The metadata answers two different questions:
- File statistics: “Could this file contain a matching customer or product?” Min/max ranges help queries rule out files.
- Clustering metadata: “Which files were produced together by clustering, and with which keys?” This record of completed work helps maintenance distinguish clustered groups from new, unclustered files.
That tracking supports incremental maintenance rather than treating every run as an instruction to reorganize all historical files. These roles are not completely separate: maintenance can also inspect value-range overlap, as Fabric’s auto reclustering does. The query benefit still comes from file organization and data skipping, not from a separate user-managed lookup tree.
The implementation details are not part of a promise that every reader uses the same clustering algorithm. The Delta protocol defines table compatibility; the versioned clustering guide describes the Spark implementation’s behavior.
Choose keys from filters, not from a list of columns
Start with predicates that matter in real workloads. A high-cardinality customer key may be a useful candidate when selective customer lookups are common. It is not automatically useful just because it has many distinct values.
The versioned Delta Lake guide allows up to four clustering columns and requires statistics on them. Check the coverage described earlier and verify your runtime’s limits rather than assuming every distribution has identical defaults.
Here are candidate choices for the same sales schema, not measured recommendations:
| Frequent workload | Candidate clustering keys | Why evaluate these keys? |
|---|---|---|
| Selective customer lookups | customer_id |
One dimension may be sufficient if customer filters already exclude most files. |
| One customer’s purchases within a date range | customer_id, transaction_date |
The date may narrow reads further when each customer has substantial history; test whether the extra dimension earns its maintenance cost. |
| Broad regional totals | Do not assume clustering is needed | A region filter may still read much of the table. Compare simple compact files, substantial region partitions, or clustering using actual read work. |
Use query frequency and selectivity together. A rare lookup need not drive the layout for a table mostly read in full. Add a second key only if the workload benefits: correlated keys can repeat the same information. The lab uses customer/product keys to compare two filter dimensions, not to prescribe them for every sales table.
Column order does not establish a first-column priority in Z-Ordering or standard liquid clustering. Unlike traditional SQL sorting, these techniques organize data across multiple dimensions; do not apply the usual leftmost-prefix intuition for composite B-tree indexes. The Delta Lake guide explicitly allows clustering columns to be defined in any order.
For example, ZORDER BY (customer_id, product_id) or CLUSTER BY (customer_id, product_id) can benefit queries filtering on customer alone, product alone, or both. A query does not need to filter on every configured column, include the first column, or write its predicates in the configured order. Actual gains depend on data distribution, predicate selectivity, available statistics, and effective file skipping. Adding more dimensions can dilute locality benefits for individual columns; more keys do not automatically mean better performance.
Liquid clustering also does not replace join-strategy tuning, fix an unselective query that reads nearly the whole table, or guarantee balanced join keys. Storage-layout skew and execution-time skew are related operational concerns, not the same problem.
What changing clustering keys really does
Suppose customer-focused lookups become less important and product-focused lookups dominate:
ALTER TABLE sales_liquid
CLUSTER BY (product_id);
This changes the policy, not the existing file contents.
Think of updating an archive’s organization guide. Writing “organize by product” on the guide does not move the boxes. New maintenance decisions can follow the new guide, but old boxes remain where they are until the appropriate reorganization happens.
Here is the crucial distinction in Delta Lake’s documented behavior:
| Operation | What changes | What not to assume |
|---|---|---|
ALTER TABLE ... CLUSTER BY (...) |
Clustering metadata | Historical files have not been rewritten |
OPTIMIZE sales_liquid |
Eligible data is incrementally clustered | Files already clustered on different keys are not automatically reclustered |
OPTIMIZE sales_liquid FULL |
Historical data is reclustered as needed to reflect the current keys | It is not an inexpensive metadata-only operation |
Do not rely on repeated ordinary OPTIMIZE runs to eventually migrate all files already clustered on old keys. The Delta Lake documentation explicitly says those files are not rewritten by the ordinary incremental operation. Use full reclustering when the historical layout must reflect the current columns.
To request historical alignment:
OPTIMIZE sales_liquid FULL;
Budget the rewrite cost of FULL; it aligns history as needed, not necessarily every byte on every invocation. The Delta Lake guide notes that when keys have not changed after a previous full operation, FULL behaves like ordinary OPTIMIZE.
You can also stop future clustering:
ALTER TABLE sales_liquid CLUSTER BY NONE;
This does not undo the existing layout or remove the table’s protocol requirements. It is not a compatibility rollback.
Side-by-side comparison
| Dimension | Hive-style partitioning | Z-Order | Liquid clustering |
|---|---|---|---|
| Main layout decision | Exact partition values, often reflected in directories | Columns supplied to an optimization operation | Clustering columns declared in table metadata |
| Main read benefit | Partition pruning; other skipping can still apply | Better locality for file-statistics skipping | Better locality for file-statistics skipping |
| High-cardinality keys | Often create too many small partitions | Can be useful for selective filters | Can be useful without exact-value partition directories |
| Multiple dimensions | Additional partition keys multiply combinations | Multidimensional locality, with trade-offs as keys increase | Multiple clustering keys; up to four in the versioned Delta Lake guide |
| Changing strategy | Usually rewrite into a new partition scheme | Reorganize relevant files using a new Z-Order column list | Change metadata first; explicitly recluster history when needed |
| Maintenance | Manage partition sizes and compact files | Schedule appropriately scoped OPTIMIZE ... ZORDER BY |
Schedule incremental OPTIMIZE; plan FULL for historical alignment |
| Can combine with the other methods? | Can combine with Z-Order | Can combine with partitioning | Not with Hive partitioning or Z-Order on the same table |
| Small-file concerns | Too many partitions can amplify them | Optimization includes file reorganization | Optimization includes file reorganization |
None of these methods removes the need to monitor file counts, write cost, statistics, and compatibility. Compaction aims to reduce small-file overhead; clustering aims to improve locality. A maintenance operation may help with both, but fewer files alone do not prove that the layout is better for your predicates.
Choose a layout for the workload you actually have
- Large table, selective customer lookups: evaluate liquid clustering on customer-related keys, especially when customer partitioning would create many tiny partitions. Z-Order remains a candidate for an existing compatible table.
- Stable date-based access with substantial data per date: a well-designed partitioned table may be entirely appropriate. Consider Z-Order within partitions if additional filters justify its cost.
- Several frequently used filter dimensions: compare a small, evidence-based set of liquid or Z-Order columns. Do not add columns just because the feature allows them.
- Changing filter patterns: liquid’s metadata-first policy changes help separate the decision from immediate rewrite work, but historical alignment still needs an explicit plan and budget.
- Small or mostly full-scan tables: begin with simple storage and healthy file sizes. Extra layout maintenance may cost more than it saves.
Do not migrate a healthy Z-Ordered table merely because liquid clustering is newer. Compare steady-state query work, maintenance cost, write behavior, and the compatibility requirements of all consumers.
Liquid clustering in Fabric Runtime 2.0
The Microsoft Fabric liquid clustering guide documents additional runtime-specific behavior, including the default incremental clustering strategy in Fabric Runtime 2.0. The current Runtime 2.0 component listing specifies Apache Spark 4.1 and Delta Lake 4.2, the environment used for the lab below. A Microsoft-specific configuration or diagnostic should not be assumed to exist in OSS Delta.
Why customers should consider it
Liquid clustering addresses how data is organized for reads; incremental liquid clustering addresses how economically that organization is maintained. In Fabric Runtime 2.0, incremental clustering is the default maintenance strategy for liquid-clustered tables, not a second table layout to enable alongside liquid clustering.
| Customer need | Why it can help |
|---|---|
| Selective queries on a large sales table | Grouping related customer/product values can narrow file-statistics ranges, allowing queries to read less irrelevant data. This can reduce read work and latency when those filters actually skip files. |
| Many distinct customers or changing access patterns | Clustering avoids a directory partition for every customer. Declared keys can change without immediately rewriting the table; align historical files separately when required. |
| Frequent appends or updates | Runtime 2.0’s incremental strategy can skip healthy, appropriately sized clustered files and focus maintenance on eligible new or changed data and other files needing attention, reducing unnecessary rewrites. |
| Clustering quality degrades as data arrives | Auto reclustering can selectively address overlapping file ranges during OPTIMIZE, reducing the need to manually plan broad reclustering solely to repair that overlap. |
For example, our sales table might receive a daily batch while analysts repeatedly filter by customer and product. Liquid clustering targets those reads; incremental maintenance can incorporate eligible new files and reorganize affected existing files rather than routinely rewriting healthy history. It is not a promise to touch only the latest batch: small files, deletes, or overlapping ranges may require additional work.
The customer value is a better balance between read efficiency and maintenance compute, I/O, and duration, not a guaranteed speedup or capacity saving. As the Fabric guide explains, selective file maintenance reduces write amplification; verify the benefit on your workload. Small or mostly full-scan tables may gain little, and a healthy partitioned or Z-Ordered table need not be migrated. You still own the OPTIMIZE schedule and must validate client compatibility.
How maintenance works in Runtime 2.0
The important decision is which files maintenance chooses to rewrite, not a new requirement to partition your data. Runtime 2.0’s incremental strategy selects unclustered, unhealthy, small, and deletion-vector files as needed, while skipping healthy, appropriately sized clustered files. Regular maintenance can therefore avoid repeatedly rewriting healthy data; still measure its cost.
Write amplification means writing much more data than the amount newly added or changed. Reorganizing an entire archive whenever one box arrives is an expensive policy; reorganizing only the boxes that need attention is the intuition behind incremental maintenance.
There are two levels of “incremental” here. Open-source Delta Lake tracks clustered file groups, rather than blindly treating all history as new. Fabric’s Runtime 2.0 strategy adds more selective file-selection and overlap-based reclustering behavior. Supporting incremental maintenance therefore does not imply identical file selection or rewrite costs across implementations. A deletion vector records rows logically removed from a file without immediately rewriting that whole file; maintenance may later rewrite such files.
Fabric Runtime 2.0 also includes auto reclustering: overlap detection selects affected files when value ranges become less useful for skipping. It runs inside OPTIMIZE when there is new or changed data to cluster. “Automatic” does not mean that declaring keys creates an independent background scheduler, selects keys for you, or clusters every write.
A hypothetical maintenance example: suppose the sales table has 100 existing clustered files, receives 10 new unclustered files, and five existing files overlap significantly with the new data.
- Incremental selection can choose the eligible new files while leaving healthy, appropriately sized existing files alone. Existing small or deletion-vector files can also qualify.
- Auto reclustering can bring affected existing files into the work when overlap meets the runtime’s rules and thresholds.
- The result is not necessarily 15 selected files. Eligibility and thresholds determine actual work; these counts describe the scenario, not expected command output.
Auto reclustering is part of incremental maintenance, not a second layout or scheduler. If there is no new or changed data to cluster, do not assume repeated OPTIMIZE calls will independently launch overlap repair. Inspect the maintenance output and quality diagnostics before deciding whether deliberate broader reclustering is warranted.
Keep the defaults first
The documented session defaults are:
spark.microsoft.delta.optimize.clustering.strategy.incremental = truespark.microsoft.delta.optimize.clustering.strategy.incremental.autoRecluster = true
Start with these defaults and compare results before tuning. The Fabric guide documents additional controls if a measured problem warrants them. The lab uses clusteringQuality() alongside actual query metrics to evaluate the result.
Other Fabric features and the compatibility boundary
Fabric documents V-Order as compatible with liquid clustering: V-Order changes organization inside files, while liquid clustering improves locality across files. They work on different axes. V-Order is not the same technique as ZORDER BY, which remains incompatible with a liquid table.
For interactions with optimize write, adaptive file sizing, auto compaction, fast optimize, and native execution, consult the Fabric compatibility guidance. These are separate considerations, not prerequisites for understanding the three layouts. The migration runbook covers client compatibility.
Try the three layouts in a disposable SQL lab
This is a functional walkthrough, not a performance benchmark. It uses 200,000 deterministic synthetic rows, intentionally small enough for exploration. Optimization may produce little visible benefit at this scale. The commands have been reviewed against the cited documentation, but this notebook sequence has not been executed in Fabric for this draft. No timings, file counts, or diagnostic outputs below are claimed as measured results.
Choose a depth within this one notebook:
- Functional route: complete steps 1–3; save the table metadata and four-row count/amount baseline in step 4; run step 5; repeat those metadata and correctness checks in step 6; then clean up. This checks commands, policy metadata, and basic data preservation, not a performance benefit or full-data equivalence.
- Diagnostic route: also capture the optional quality baseline and query measurements in step 4 before step 5. In step 6, repeat them and run the stronger full-data comparisons. Step 7 is a separate, optional key-change experiment.
Keep the same tables and session for both routes. If you skip the diagnostic baseline, do not claim a before/after comparison later; rerunning the inserts would append duplicate rows, not restore the initial state. Both routes require the setup safeguards and cleanup.
1. Start a compatible environment
Recommended for customers: use Microsoft Fabric Runtime 2.0, which provides Apache Spark 4.1 and Delta Lake 4.2 as a managed service. This avoids assembling and maintaining a local Spark, Java, Scala, and Delta installation just to explore the layout techniques. Fabric capacity usage and storage still have costs; managed does not mean free or that table maintenance schedules itself.
To get started:
- Create or open a Fabric Environment item, select 2.0 (Spark 4.1, Delta 4.2), then save and publish it.
- Attach that environment to a notebook. Attach a disposable, schema-enabled lakehouse and set it as the notebook’s default lakehouse. An attached environment’s runtime overrides the workspace default; validate existing libraries and workloads before upgrading.
- Use the runtime-provided Delta libraries. Do not install a separate Delta package into Fabric.
- Keep the notebook’s default language PySpark. Paste each
%%sqlblock into its own code cell, including the magic on the first line.%%sparkselects Scala for the diagnostic cell. These are Spark notebook commands, not SQL analytics endpoint/T-SQL scripts.
See the Runtime 2.0 setup instructions for workspace-level selection and environment configuration.
Every persistent lab table uses dbo.delta_layout_*. In a schema-enabled Fabric lakehouse, dbo exists by default; the omitted workspace and lakehouse resolve from the notebook context. This lab does not create, switch, or drop a database. Keep the same default lakehouse and Spark session throughout.
Confirm these three table names do not already exist. The CREATE TABLE statements intentionally fail on an existing name; do not replace them with OR REPLACE or drop an unfamiliar table. If necessary, choose a fresh prefix and update every reference, including diagnostics and cleanup.
2. Create deterministic source rows
Run this in the notebook’s Spark session. The source is a session-scoped temporary view, not another persistent lakehouse table.
%%sql
CREATE OR REPLACE TEMP VIEW delta_layout_source AS
SELECT
id AS transaction_id,
pmod(xxhash64(id, 'customer'), 10000) AS customer_id,
CASE pmod(id, 3)
WHEN 0 THEN 'US'
WHEN 1 THEN 'UK'
ELSE 'IN'
END AS region,
pmod(xxhash64(id, 'product'), 1000) AS product_id,
date_add(DATE '2026-01-01', CAST(pmod(id, 90) AS INT))
AS transaction_date,
CAST(pmod(id, 10000) / 100.0 AS DECIMAL(12, 2)) AS amount
FROM range(200000);
pmod produces a nonnegative remainder. The separately salted hashes avoid making product ID just a simple remainder of customer ID. This is synthetic teaching data, not a model of real sales distributions.
3. Create and populate three independent tables
%%sql
CREATE TABLE dbo.delta_layout_partitioned (
transaction_id BIGINT, customer_id BIGINT, region STRING,
product_id BIGINT, transaction_date DATE, amount DECIMAL(12, 2)
)
USING DELTA
PARTITIONED BY (region);
CREATE TABLE dbo.delta_layout_zordered (
transaction_id BIGINT, customer_id BIGINT, region STRING,
product_id BIGINT, transaction_date DATE, amount DECIMAL(12, 2)
)
USING DELTA;
CREATE TABLE dbo.delta_layout_liquid (
transaction_id BIGINT, customer_id BIGINT, region STRING,
product_id BIGINT, transaction_date DATE, amount DECIMAL(12, 2)
)
USING DELTA
CLUSTER BY (customer_id, product_id);
INSERT INTO dbo.delta_layout_partitioned SELECT * FROM delta_layout_source;
INSERT INTO dbo.delta_layout_zordered SELECT * FROM delta_layout_source;
INSERT INTO dbo.delta_layout_liquid SELECT * FROM delta_layout_source;
Run the inserts once; rerunning them appends duplicate rows. All six columns are within the default statistics range. Keep the datasets separate: the lab is not trying to apply mutually exclusive layouts to a single table.
4. Save the baseline before optimization
%%sql
DESCRIBE DETAIL dbo.delta_layout_partitioned;
DESCRIBE DETAIL dbo.delta_layout_zordered;
DESCRIBE DETAIL dbo.delta_layout_liquid;
Save each result before proceeding. Inspect partitionColumns, clusteringColumns, numFiles, protocol fields, and table features where exposed. The relevant metadata should have this shape; this is a selected-field expectation, not captured output:
| Table suffix | partitionColumns |
clusteringColumns |
|---|---|---|
partitioned |
["region"] |
Empty or not applicable |
zordered |
[] |
Empty or not applicable; Z-Order is not a declared clustering policy |
liquid |
[] |
["customer_id", "product_id"] |
Capture the logical answer too:
%%sql
SELECT 'source' AS layout, COUNT(*) AS rows, SUM(amount) AS total_amount
FROM delta_layout_source
UNION ALL
SELECT 'partitioned', COUNT(*), SUM(amount)
FROM dbo.delta_layout_partitioned
UNION ALL
SELECT 'zordered', COUNT(*), SUM(amount)
FROM dbo.delta_layout_zordered
UNION ALL
SELECT 'liquid', COUNT(*), SUM(amount)
FROM dbo.delta_layout_liquid;
Expected: four rows, each with rows = 200000 and total_amount = 9999000.00; row order is not specified. These totals follow from the source formula, not a measured run. Reorganizing files must not change them.
Optional diagnostic route: capture the Fabric-only quality baseline in a Scala cell:
%%spark
import io.delta.tables.DeltaTable
display(
DeltaTable.forName(spark, "dbo.delta_layout_liquid").clusteringQuality()
)
It returns one row per clustering column, so two for this policy. Save the output. A field such as status = no_stats is diagnostic feedback, not proof that the table has no data.
Measure the layout, not just the stopwatch
Before optimization, run the same query mix on all three tables. Region partitioning and customer/product clustering intentionally favor different filters; one favorable query cannot establish a winner.
This subsection is for the diagnostic route. For the functional route, continue to step 5 after saving the metadata and count/amount baseline above.
Predict before you run the combined filter region = 'US' AND customer_id = 42:
- Now, before optimization: the partitioned table can rule out the UK and IN partitions. The other two tables will probably skip little, because customer IDs are not yet grouped into files.
- After step 5: customer-ID ranges on the Z-Ordered and liquid tables may narrow, so file statistics may rule out files whose range excludes 42.
- Region alone is unlikely to provide much file skipping on the non-partitioned tables in this synthetic dataset. The source cycles through regions with
pmod(id, 3), but source row order does not guarantee output-file contents, especially after redistribution. Inspect actual file statistics rather than assuming every file contains all three regions.
A remaining candidate file is not a match: Spark still applies the query conditions to find qualifying rows.
Inspect the same combined-filter plan on every layout:
%%sql
EXPLAIN FORMATTED
SELECT SUM(amount) FROM dbo.delta_layout_partitioned WHERE region = 'US' AND customer_id = 42;
EXPLAIN FORMATTED
SELECT SUM(amount) FROM dbo.delta_layout_zordered WHERE region = 'US' AND customer_id = 42;
EXPLAIN FORMATTED
SELECT SUM(amount) FROM dbo.delta_layout_liquid WHERE region = 'US' AND customer_id = 42;
In each plan, find the scan node for the table. On the partitioned table, PartitionFilters should include the region condition. DataFilters describes data-filter conditions, while PushedFilters identifies filters passed to the underlying reader, such as Parquet. These are not evidence that clustering caused Delta files to be skipped: Delta file skipping uses file statistics. Check available executed scan metrics to measure files or bytes actually read. Exact plan labels vary by execution engine.
Then run the queries without EXPLAIN FORMATTED to execute them. Repeat across every table for the individual filters region = 'US', customer_id = 42, and product_id = 7, retaining the same aggregate and checking that answers match. For a real workload, weight this mix by query frequency.
In the Fabric notebook’s completed Spark execution, open Spark UI, inspect the query under SQL / DataFrame, and examine its executed scan details and associated stages. Save exposed input bytes, records, scan/file metrics, and elapsed time. A plan alone does not prove bytes were skipped; unavailable metrics should be marked unavailable, not inferred from latency.
For representative performance testing beyond this small lab, record runtime/compute configuration, data volume, file sizes/compression, cache state, and concurrency. Keep these conditions comparable, repeat the runs, and include queries that omit the layout keys or read most of the table. Save the baseline now; the optimized table cannot reconstruct it afterward.
5. Run maintenance with the original keys
%%sql
OPTIMIZE dbo.delta_layout_partitioned;
OPTIMIZE dbo.delta_layout_zordered ZORDER BY (customer_id, product_id);
OPTIMIZE dbo.delta_layout_liquid;
Keep all three maintenance outputs. Record elapsed time, compute usage, available bytes/files rewritten, and temporary storage or write-conflict observations. Compare the read benefit against this write cost.
6. Compare correctness, layout, and read work
Both routes: rerun the three DESCRIBE DETAIL statements and the four-row correctness query. Diagnostic route: also rerun the Scala quality cell and your query mix from step 4 under comparable conditions. Save results as after without overwriting the baseline. Do not change keys yet: both quality snapshots must describe the same policy.
Optional diagnostic route: for a stronger full-data check on this small lab, compare both directions with EXCEPT ALL:
%%sql
SELECT * FROM delta_layout_source
EXCEPT ALL
SELECT * FROM dbo.delta_layout_liquid;
SELECT * FROM dbo.delta_layout_liquid
EXCEPT ALL
SELECT * FROM delta_layout_source;
Both should return zero rows. Repeat for the other two tables. ALL matters because it preserves duplicate multiplicities when comparing datasets.
What success looks like:
- Metadata: the declared partition/clustering columns match the intended design.
- Correctness: counts, amounts, and full-data comparisons remain unchanged.
- Layout: file-statistics coverage and overlap may improve; fewer files alone do not prove this.
- Performance: only representative executed queries can establish a reduction in read work or latency.
Why you may see no improvement: 200,000 narrow rows can fit into one or very few files. With one candidate file, there may be little file-skipping headroom; write-time optimizations may already produce healthy files, and fast optimize can skip insufficient eligible data. An unchanged file count or a no-op is not automatically a failure. Inspect the maintenance output before scaling up, and do not manufacture tiny files merely to create a favorable result.
To recognize a read-work improvement, imagine running the same selective query on the same logical data before and after reorganizing a table. These numbers are hypothetical, not expected output from this small lab or captured benchmark results:
| Metric | Before | After |
|---|---|---|
| Total active files | 100 | 100 |
| Files remaining candidates after file skipping | 80 | 12 |
| Files excluded by file skipping | 20 | 88 |
| Query result | Same answer | Same answer |
The improvement is fewer candidate files, not necessarily fewer files in the table. Candidate files may still contain no matching rows. These counts do not imply a proportional reduction in bytes or latency: file sizes, caching, and other query work also matter.
Interpret clusteringQuality() separately as estimated skipping potential, not measured latency or actual query skip counts. Compare both key rows. Lower avg_coverage_pct, avg_depth, max_depth, and overlap_ratio, and higher skipping_effectiveness, are generally favorable, interpreted with the data distribution and number of clustering dimensions.
| Observation | Next action |
|---|---|
status = no_stats, or few files with statistics |
Check column eligibility, statistics-column coverage, and the runtime’s supported statistics collection procedure. Existing files do not gain missing statistics merely because keys were declared; see Fabric file-skipping guidance. |
| Overlap stays high | Confirm the keys match selective filters, inspect skew and key correlation, and review which files maintenance selected. Do not start by lowering reclustering thresholds. |
| Optimization selects no files | Check whether there is new/changed eligible data and whether the table is already compact or too small for useful clustering. A no-op can be correct. |
| Quality improves but latency does not | Inspect actual scan metrics, caching, planning overhead, joins, and other bottlenecks before increasing maintenance. |
For production, also validate an append/merge cycle and subsequent maintenance at equivalent snapshots. Start the maintenance schedule from the ingestion pattern: a daily batch could evaluate one incremental optimization after its batch, then adjust using read work, rewrite cost, and duration. Continuous ingestion needs a separately budgeted maintenance window, not FULL after every microbatch.
7. Change the liquid policy deliberately
This experiment is optional for both routes. Finish and save your chosen comparisons first; otherwise continue to cleanup.
Checkpoint 1: verify the policy. After saving the original-key comparison, change the keys and inspect the table definition:
%%sql
ALTER TABLE dbo.delta_layout_liquid CLUSTER BY (product_id);
DESCRIBE DETAIL dbo.delta_layout_liquid;
Expect clusteringColumns to contain only product_id. This confirms the new policy, not a rewrite of historical files.
Checkpoint 2: inspect physical work. Run the following in a separate cell and save the OPTIMIZE result:
%%sql
OPTIMIZE dbo.delta_layout_liquid FULL;
Look for files removed and added in the result, or inspect the optimization entry in DESCRIBE HISTORY dbo.delta_layout_liquid for available operation metrics. Replacing two files with two others leaves the total file count unchanged, so that count alone cannot show whether a rewrite happened. If no files were rewritten, record that observation rather than claiming the layout improved.
Rerun the step 4 correctness query: each table should still have 200,000 rows totaling 9,999,000.00. The quality diagnostic now describes one key, so its output is not a like-for-like comparison with the two-key baseline.
Clean up after all measurements
The following cell deletes the three managed lab tables and their managed data. Run it only after saving all outputs and confirming that the notebook still points at the same disposable default lakehouse. It does not remove a schema, lakehouse, or unrelated tables.
%%sql
DROP TABLE dbo.delta_layout_partitioned;
DROP TABLE dbo.delta_layout_zordered;
DROP TABLE dbo.delta_layout_liquid;
DROP VIEW delta_layout_source;
Do not copy this cleanup into an environment containing real data. The migration examples below are a separate advanced runbook, not a continuation of this notebook.
Migrating an existing Z-Ordered table
Treat migration as a compatibility and operating-model change, with acceptance criteria and a recovery path.
The snippets use two illustrative names: sales_source is the original Z-Ordered table, inspected read-only; sales_migration_candidate is a separate test table used for changes and validation. Neither is created by the lab. Substitute qualified catalog names and verify the target before running any write or maintenance command.
1. Inspect the source and record a baseline
DESCRIBE DETAIL sales_source;
DESCRIBE HISTORY sales_source;
Save the source version, partition columns, protocol/features, size, file count, and recent operations. Read history from the source, not its copy: a new candidate has its own transaction log. Z-Order keys are not a persistent clustering policy, so inspect history parameters and scheduled job definitions to recover the existing choices. See the Delta table utility guide for interpreting these outputs.
Distinguish two starting points:
| Existing table | Migration path documented by Delta Lake |
|---|---|
| Unpartitioned, previously Z-Ordered | Delta 3.3+ supports enabling clustering with ALTER TABLE ... CLUSTER BY (...), after compatibility checks |
| Hive-partitioned, with or without Z-Order | Do not use the unpartitioned enablement shortcut; plan a supported rewrite into a separate unpartitioned, liquid-clustered target |
Do not move directories manually or assume a platform-specific conversion command is available in open-source Delta Lake. Set acceptance criteria using the lab’s baseline and measurement approach, adding ingestion and client checks for your production workload.
2. Gate the change on compatibility and recovery
Before enabling clustering, verify every reader and writer against the table’s Delta protocol: its compatibility contract and enabled features. Spark support alone does not establish support in SQL endpoints, Direct Lake/BI models, or external connectors. Include streaming and maintenance clients; reading raw Parquet does not establish correct Delta snapshot handling.
Choose the deployment approach before changing the source:
- In-place enablement: avoids an initial parallel data copy but changes the original table’s metadata and protocol requirements. An unchanged source is no longer available as a fallback unless you separately preserved one.
- Parallel-table migration: retain the original table, create a separate clustered candidate, copy a defined source snapshot, and validate before switching consumers. Budget the additional storage, copy compute, permissions, and synchronization work.
A parallel candidate keeps an unchanged source available, but becomes stale as writes arrive. Define the ingestion pause or catch-up boundary to prevent missed or duplicated changes. A shared-file clone or version reference is not automatically an independent backup; verify file ownership and retention.
3. Choose keys and replace maintenance together
Start with your current ZORDER BY columns, plus any partition columns, as the Delta Lake guide recommends. Then confirm they still match your most important filters using the earlier key-selection guidance. If the combined list exceeds the runtime’s supported clustering-column limit, prioritize the most useful, nonredundant filter columns rather than copying the whole list.
Pause or replace old optimization schedules before enabling clustering, so no job races the change with an incompatible ZORDER BY operation. For a parallel migration, create the candidate as an unpartitioned, clustered copy of a recorded source version:
CREATE TABLE sales_migration_candidate
USING DELTA
CLUSTER BY (customer_id, transaction_date)
AS SELECT * FROM sales_source VERSION AS OF <recorded_version>;
DESCRIBE DETAIL sales_migration_candidate;
Replace <recorded_version> with the version saved in step 1, and confirm that retention still keeps it readable. The Fabric guide documents CREATE TABLE ... CLUSTER BY ... AS SELECT. Because the new table has no PARTITIONED BY clause, the same pattern works for a Hive-partitioned source. Do not assume the copy is clustered as it is written; run OPTIMIZE and inspect the result.
For the parallel-candidate path, replace the candidate’s old OPTIMIZE ... ZORDER BY (...) maintenance, if any, with:
OPTIMIZE sales_migration_candidate;
For in-place enablement, do not create or target a separate candidate. After approval, use ALTER TABLE <approved_existing_table> CLUSTER BY (...), documented from Delta Lake 3.3, and run subsequent OPTIMIZE operations against that same existing table. The candidate-named commands here apply only to the parallel path.
Update shared templates, retries, ad hoc runbooks, and orchestration as well as the primary schedule. Assign an owner, maintenance window, monitoring, and cost limit.
4. Decide how much historical reorganization is necessary
After in-place enablement, existing Z-Ordered files retain their locality; they do not become proof of a liquid-clustered history merely because keys match. Observe incremental maintenance, and defer broader reorganization if the current layout meets your acceptance criteria. A parallel copy has no inherited Z-Ordered files, but still verify the OPTIMIZE result rather than assuming the copy is clustered. When history must align with the new policy, the parallel-candidate path uses:
OPTIMIZE sales_migration_candidate FULL;
For the in-place path, run OPTIMIZE <approved_existing_table> FULL against the same table altered in step 3, not sales_migration_candidate. Budget I/O, compute, and temporary storage, and measure actual rewrite work. For a later key change on an already liquid-clustered table, use the earlier historical-alignment guidance.
5. Validate, cut over, and retain a usable fallback
Repeat the baseline checks at equivalent snapshots, including append/merge and streaming behavior. Require demonstrated read or maintenance benefits rather than a feature being enabled.
For a parallel migration, verify permissions and dependent views/jobs, reconcile writes through the agreed boundary, and rehearse consumer cutover using supported routing. Stream checkpoints and offsets are not automatically portable to another Delta table; validate a restart or continuation plan without gaps or duplicates.
Assign a rollback window and owner. Retain the original table and required data/log files; ensure cleanup or VACUUM cannot remove the recovery path during that window. Budget that retention rather than disabling safeguards.
Reconcile post-cutover writes before routing back. Otherwise the fallback can return stale data even if its layout still works.
Neither CLUSTER BY NONE nor routine RESTORE is a guaranteed compatibility rollback. The versioned restore implementation preserves protocol requirements by default; feature removal and downgrade support must be verified for the deployed platform.
Adoption checklist
- Choose keys from important filters, data distribution, and available statistics.
- Verify client compatibility and identical logical results.
- Compare representative read benefits against maintenance cost.
- Replace legacy Z-Order jobs and assign an optimization owner and budget.
- Plan historical alignment and rehearse migration, recovery, and retention.
Final takeaway
The simplest way to remember the difference is:
- Hive-style partitioning: choose exact-value groups so partition metadata can rule out groups.
- Z-Order: reorganize relevant files around selected dimensions so statistics can rule out more files.
- Liquid clustering: declare and maintain a clustering policy, with incremental tracking and metadata-first key changes.
Liquid clustering’s flexibility is real, but it is not free physical reorganization. Changing a policy and converging historical data to that policy are separate decisions.
Start with one important filter, inspect the current layout, and test whether a better layout reduces actual read work enough to justify maintaining it.
Further reading
- Delta Lake: liquid clustering. Covers enablement, key changes, statistics requirements, and incremental versus full maintenance. Consult the documentation matching your deployed version.
- Delta Lake: optimization and data skipping. Explains compaction, Z-Order, and file statistics.
- Delta Lake: partitioning best practices. Provides partition-cardinality and size heuristics to validate against your workload.
- Microsoft Fabric: liquid clustering. Covers Runtime 2.0 maintenance, defaults, quality diagnostics, and optimization compatibility.
- Microsoft Fabric Runtime 2.0 and lakehouse schemas. Explain the managed components, notebook environment, and lab namespace.
- Fabric file skipping. Explains statistics coverage and when readers can reject files.
- Delta table utilities. Supports migration preflight, history inspection, and recovery planning.
Note: This blog post was written with assistance from AI