OPTIMIZE

Applies to: check marked yes Databricks SQL check marked yes Databricks Runtime

OPTIMIZE optimizes the layout of data in Delta Lake tables and managed Apache Iceberg tables. You can optimize a subset of data or collocate data by column. If you don't specify collocation and the table doesn't use liquid clustering, Delta Lake performs bin-packing optimization.

Use OPTIMIZE table_name EXTENDED to run workload-based optimization on demand. See Optimize table layout with OPTIMIZE EXTENDED.

Syntax

OPTIMIZE table_name [FULL] [WHERE predicate]
  [ZORDER BY (col_name1 [, ...] ) ]

OPTIMIZE table_name EXTENDED

Note

Bin-packing optimization is idempotent: if you run it twice on the same data set, the second run has no effect. It produces evenly-balanced data files with respect to their size on disk, but not necessarily the number of tuples per file. The two measures are most often correlated.

Z-Ordering is not idempotent, but operates incrementally. The time Z-Ordering takes is not guaranteed to decrease over multiple runs. However, if no new data was added to a partition that was just Z-Ordered, running Z-Ordering again on that partition has no effect. Z-Ordering produces evenly-balanced data files with respect to the number of tuples, but not necessarily data size on disk. The two measures are most often correlated, but skew in optimize task times can occur when they diverge.

Note

When using Databricks Runtime, to control the output file size, set the Spark configuration spark.databricks.delta.optimize.maxFileSize. The default value is 1073741824 (1 GB). Specifying 104857600 sets the file size to 100 MB.

Parameters

  • table_name

    Identifies an existing Delta Lake table or managed Apache Iceberg table. The name must not include a temporal specification or options specification.

  • EXTENDED

    Important

    This feature is in Beta. To use it, a workspace admin must turn on OPTIMIZE EXTENDED from the Previews page. See Manage Azure Databricks previews.

    Applies to: check marked yes Databricks SQL check marked yes Databricks Runtime 19 and above

    Runs applicable workload-based optimization operations on demand and returns their results.

    On a table with automatic liquid clustering, the command runs clustering-key selection and clustering. On other tables, it returns a clustering recommendation without applying the recommended keys. Applicable file compaction and statistics collection can also run.

    When scheduling a new clustering operation for a liquid-clustered table, EXTENDED uses OPTIMIZE FULL for tables up to 10 TB. It uses incremental OPTIMIZE for larger tables or when the table size is unknown. An existing pending or running clustering operation is reused without changing its mode. See Force reclustering.

    For clustering-key selection and recommendations, EXTENDED uses a 1-day query-history lookback by default. Run representative queries before running the command.

    When EXTENDED finds a potentially better layout and schedules validation, it saves the query-history starting point for later automatic clustering decisions. This starting point remains saved even if validation fails or the clustering keys stay the same.

    You must own the table or have the MODIFY privilege on it, including when the command returns only a clustering recommendation.

    The table must have predictive optimization enabled. Use a named table reference. Path-based references, materialized views, and streaming tables are not supported. You cannot combine EXTENDED with FULL, WHERE, ZORDER BY, or DRY RUN.

    The command uses billable predictive optimization compute and waits for triggered operations to finish. See EXTENDED output and Optimize table layout with OPTIMIZE EXTENDED.

  • FULL

    Applies to: check marked yes Databricks Runtime 16.0 and above

    Rewrites existing data files so that they match the table's current layout settings. Use OPTIMIZE table_name FULL to:

    • Recluster existing data after you enable liquid clustering or change the clustering keys. 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. If the clustering keys have not changed, OPTIMIZE table_name FULL clusters the same files as OPTIMIZE table_name. See Force reclustering.
    • Recompress existing data files when you change the table's compression codec using the delta.parquet.compression.codec property.

    To recompress existing data after changing the compression codec, run OPTIMIZE table_name FULL:

    -- Change compression codec
    ALTER TABLE table_name SET TBLPROPERTIES ('delta.parquet.compression.codec' = 'ZSTD');
    
    -- Recompress all existing data files
    OPTIMIZE table_name FULL;
    

    To optimize a subset of files in a table with liquid clustering enabled, combine FULL with a WHERE predicate (Databricks Runtime 18.1 and above). Only simple range predicates on a single clustering column are supported. A file is included if any part of its range overlaps with the predicate. For example, OPTIMIZE events FULL WHERE date > 15 includes a file with range (col_min = 10, col_max = 20) because the file's range overlaps with the predicate. Of the included files, FULL WHERE rewrites only the files that FULL would rewrite. Files that are already clustered with the current clustering keys are not rewritten.

  • WHERE

    Optimizes the subset of rows matching a partition / clustering predicate. Only filters on partition / clustering key attributes are supported.

    For tables that use liquid clustering, use OPTIMIZE table_name FULL WHERE predicate (Databricks Runtime 18.1 and above) instead.

  • ZORDER BY

    Note

    Databricks recommends liquid clustering for all new tables instead of Z-ordering. See Use liquid clustering for tables.

    Collocates column information in the same set of files. Delta Lake data-skipping algorithms use co-locality to reduce the amount of data that needs to be read. You can specify multiple columns as a comma-separated list, but the effectiveness of co-locality decreases with each additional column.

    You can't use this clause on tables that use liquid clustering or on Apache Iceberg tables.

EXTENDED output

OPTIMIZE table_name EXTENDED returns one row per reported operation:

Column Type Description
operation_type STRING The operation evaluated or run.
operation_id STRING The operation identifier. NULL for operations skipped before scheduling.
status STRING The outcome: SUCCESS, FAILED, or SKIPPED.
detail STRING A JSON metrics object for an operation that ran, or a plain-text skip reason. An operation without returned metrics has {}.

Applicable operation types include AUTO_CLUSTERING_COLUMN_SELECTION, AUTO_CLUSTERING_RECOMMENDATION, CLUSTERING, COMPACTION, ANALYZE, and DATA_SKIPPING_COLUMN_SELECTION. The operation set varies by table and applicable work. A successful operation can rewrite no files.

For example, a successful compaction that rewrites no files has this detail:

{
  "amount_of_output_data_bytes": "0",
  "amount_of_data_compacted_bytes": "0",
  "number_of_output_files": "0",
  "number_of_compacted_files": "0"
}

An operation skipped before scheduling can instead return the following plain-text detail with status = 'SKIPPED' and operation_id = NULL:

No eligible scan metrics found in the time window for column selection

Parse detail as JSON only when it contains a metrics object. Copy a non-null operation_id to inspect the corresponding history record. See How much compute did an OPTIMIZE EXTENDED run use?.

Clustering-key selection details

AUTO_CLUSTERING_COLUMN_SELECTION can return the following fields when the corresponding metrics are available. Values are strings.

Field Description
has_column_selection_changed "true" if the selected keys changed, or "false" if they did not.
old_clustering_columns The previous clustering columns.
new_clustering_columns The selected clustering columns. Omitted when the keys do not change.
additional_reason An explanation of the selection or the decision to retain the keys.

The following example shows a selection from insertion order:

{
  "has_column_selection_changed": "true",
  "old_clustering_columns": "",
  "new_clustering_columns": "customer_id",
  "additional_reason": "New scheme is better than insertion order."
}

Clustering recommendation details

AUTO_CLUSTERING_RECOMMENDATION returns the following fields. Values are strings, including numeric rates. current_layout contains a JSON-encoded object.

Field Description
current_layout The existing partition_columns, clustering_columns, and hierarchical_clustering_columns. Absent values within this object are null.
current_pruning_rate The estimated data-skipping rate of the existing layout.
top_evaluated_clustering_columns The clustering columns of the best evaluated candidate.
top_evaluated_hierarchical_clustering_columns The candidate's hierarchical columns in priority order. Empty for a standard clustering layout.
top_evaluated_pruning_rate The estimated data-skipping rate of the best evaluated candidate.
calculated_pruning_improvement The top evaluated pruning rate minus the current pruning rate.
recommended_clustering_columns The recommended clustering columns. Empty when no change is recommended.
recommended_hierarchical_clustering_columns The recommended hierarchy in priority order. Empty when no hierarchy is recommended.

Rates use six decimal places. Unavailable rates or column lists are empty strings. A candidate can appear in the top-evaluated fields even when no change is recommended.

The following example recommends a hierarchy that prioritizes a before b:

{
  "current_layout": "{\"partition_columns\":null,\"clustering_columns\":null,\"hierarchical_clustering_columns\":null}",
  "current_pruning_rate": "0.000000",
  "top_evaluated_clustering_columns": "`a`,`b`",
  "top_evaluated_hierarchical_clustering_columns": "`a`,`b`",
  "top_evaluated_pruning_rate": "0.939542",
  "calculated_pruning_improvement": "0.939542",
  "recommended_clustering_columns": "`a`,`b`",
  "recommended_hierarchical_clustering_columns": "`a`,`b`"
}

These rates estimate pruning for the evaluated workload. An improvement of 0.939542 is about 93.95 percentage points of estimated pruning, not a measured query speedup. The recommendation does not apply the keys.

Examples

> OPTIMIZE events;

> OPTIMIZE events FULL;

> -- Select keys and optimize on demand
> OPTIMIZE main.benchmark.orders EXTENDED;

> -- Partitioned table
> OPTIMIZE events WHERE date >= '2017-01-01';

> -- Table with liquid clustering enabled (DBR 18.1 and above)
> OPTIMIZE events FULL WHERE date >= '2025-01-01';

> OPTIMIZE events
    WHERE date >= current_timestamp() - INTERVAL 1 day
    ZORDER BY (eventType);

For more information, see Optimize data file layout and Optimize managed Iceberg tables.