> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to keep FINAL queries fast on ReplacingMergeTree

> Make SELECT ... FINAL on ReplacingMergeTree read less data: filter on the leading sorting key columns, keep the partition key inside the sorting key, and know the related settings.

Background merges of a `ReplacingMergeTree` table remove old row versions eventually, so at any moment the table can still contain several versions of a row. `SELECT ... FINAL` returns the deduplicated result at query time. Its cost depends on how many rows it has to read and merge, so the way to keep it fast is to let the query skip data before deduplication starts: filter on the leading columns of the sorting key, and make the partition key part of the sorting key.

## Example table

```sql theme={null}
CREATE TABLE orders
(
    customer_id UInt32,
    created_at DateTime,
    order_id UInt64,
    status LowCardinality(String),
    amount Decimal(18, 2),
    updated_at DateTime
)
ENGINE = ReplacingMergeTree(updated_at)
PARTITION BY toYYYYMM(created_at)
ORDER BY (customer_id, created_at, order_id);

-- Keep the parts as inserted, so that the numbers below are reproducible.
SYSTEM STOP MERGES orders;

-- 1,000,000 orders of 10,000 customers, spread over six months.
INSERT INTO orders
SELECT
    number % 10000,
    toDateTime('2026-01-01 00:00:00') + INTERVAL (number % 180) DAY,
    number,
    'new',
    number % 500,
    toDateTime('2026-07-01 00:00:00')
FROM numbers(1000000);

-- A newer version of every tenth order.
INSERT INTO orders
SELECT
    number % 10000,
    toDateTime('2026-01-01 00:00:00') + INTERVAL (number % 180) DAY,
    number,
    'shipped',
    number % 500,
    toDateTime('2026-07-02 00:00:00')
FROM numbers(1000000)
WHERE number % 10 = 0;
```

The table now holds 1,100,000 rows in 12 parts (two per month), and `SELECT count() FROM orders FINAL` returns 1,000,000.

## Filter on the leading sorting key columns

`FINAL` only has to deduplicate the ranges that the primary index selects. `EXPLAIN ESTIMATE` shows how much a query reads. A filter on a column that is not in the sorting key reads the whole table:

```sql theme={null}
EXPLAIN ESTIMATE
SELECT sum(amount) FROM orders FINAL WHERE status = 'shipped';
```

```text theme={null}
   ┌─database─┬─table──┬─parts─┬────rows─┬─marks─┐
1. │ default  │ orders │    12 │ 1100000 │   134 │
   └──────────┴────────┴───────┴─────────┴───────┘
```

A filter on the first column of the sorting key reads one granule per part:

```sql theme={null}
EXPLAIN ESTIMATE
SELECT sum(amount) FROM orders FINAL WHERE customer_id = 42;
```

```text theme={null}
   ┌─database─┬─table──┬─parts─┬───rows─┬─marks─┐
1. │ default  │ orders │    12 │ 104142 │    12 │
   └──────────┴────────┴───────┴────────┴───────┘
```

Choose the sorting key so that it starts with the columns your `FINAL` queries filter on, followed by the columns that identify a row.

## Keep the partition key inside the sorting key

In the example, the partition key `toYYYYMM(created_at)` uses only a column of the sorting key. Rows with the same sorting key therefore always land in the same partition, and ClickHouse uses this in two ways.

Partitions are pruned before `FINAL`:

```sql theme={null}
EXPLAIN ESTIMATE
SELECT sum(amount) FROM orders FINAL WHERE created_at >= '2026-06-01 00:00:00';
```

```text theme={null}
   ┌─database─┬─table──┬─parts─┬───rows─┬─marks─┐
1. │ default  │ orders │     2 │ 172205 │    21 │
   └──────────┴────────┴───────┴────────┴───────┘
```

Each partition is deduplicated on its own instead of merging all parts of the table together. A partition that consists of a single merged part is read without any deduplication work, so a month that has already been merged into one part costs the same as without `FINAL`. ClickHouse decides this automatically when [`enable_automatic_decision_for_merging_across_partitions_for_final`](https://clickhouse.com/docs/reference/settings/session-settings/enable#enable_automatic_decision_for_merging_across_partitions_for_final) is on (the default). For this decision it looks at the primary key, not at the whole sorting key: if the table has an explicit `PRIMARY KEY` that is shorter than `ORDER BY`, the columns of the partition key must be in the `PRIMARY KEY` as well. With `PRIMARY KEY customer_id` on the example table, partitions are still pruned, but the parts of all the remaining partitions are merged together.

If the partition key uses a column that is not in the sorting key, neither happens. On a copy of this table with `ORDER BY (customer_id, order_id)`, the query above reads all 12 parts and 1,100,000 rows: since version 26.3, partitions are not pruned for `FINAL` on such a table, because two versions of a row could be in different partitions. If you know that all versions of a row always stay in one partition, you can change that by hand:

* [`do_not_merge_across_partitions_select_final = 1`](https://clickhouse.com/docs/reference/settings/session-settings/other#do_not_merge_across_partitions_select_final) prunes partitions and deduplicates every partition separately. On the copy of the table, the query then reads 2 parts and 172,205 rows again.
* [`defer_partition_pruning_after_final = 0`](https://clickhouse.com/docs/reference/settings/session-settings/other#defer_partition_pruning_after_final) only brings back partition pruning.

Both settings can return duplicates or outdated versions if that assumption does not hold. The partition key of an existing table cannot be changed; to repartition, create a new table and copy the data.

> [!WARNING]
>
> Add a partition column to the sorting key only if its value never changes between the versions of a row. The sorting key is what identifies a row in `ReplacingMergeTree`: two rows that differ in any sorting key column are different rows and are never deduplicated. With `PARTITION BY month ORDER BY (id, month)`, an order that gets a new version with another `month` stays in the result of `FINAL` twice, once for each month. With `ORDER BY id`, the query returns only the newer version.

## What ClickHouse already does for you

Upgrading is often the cheapest optimization. These changes need no action, unless the [`compatibility`](https://clickhouse.com/docs/reference/settings/session-settings/compatibility#compatibility) setting pins an older version:

| Version | Change |
| - | - |
| 23.12 | Part ranges that do not overlap by sorting key with other parts are read without the merge step of `FINAL`. With few duplicates, a `FINAL` query costs almost the same as one without `FINAL`. |
| 25.6 | Data skipping indexes are used with `FINAL` (`use_skip_indexes_if_final`, `use_skip_indexes_if_final_exact_mode`). |
| 25.10 | For tables with an `is_deleted` column, single-part partitions and non-overlapping part ranges also skip the merge step of `FINAL`. |
| 26.9 | `FINAL` queries that sort in reverse order of the sorting key, such as `ORDER BY key DESC LIMIT n`, read the data in that order instead of sorting it (`optimize_read_in_reverse_order_final`). |
| 26.10 | Conditions on sorting key columns are moved to `PREWHERE` with `FINAL` (`optimize_move_to_prewhere_if_final`). |

Two more settings are worth knowing:

* [`max_final_threads`](https://clickhouse.com/docs/reference/settings/session-settings/max#max_final_threads) limits the number of threads that read data for a `FINAL` query. The default is the number of CPU cores, so check that a settings profile does not lower it.
* [`query_plan_optimize_lazy_final`](https://clickhouse.com/docs/reference/settings/session-settings/query-plan#query_plan_optimize_lazy_final) (added in 26.4, off by default) can help queries whose `WHERE` condition matches few rows. ClickHouse first collects the primary keys of the rows that match the condition, uses them to narrow down the ranges that `FINAL` has to process, and reads the remaining columns only for the rows that are left. It falls back to the regular `FINAL` when the condition is not selective enough.

## Related pages

* [`ReplacingMergeTree` guide](https://clickhouse.com/docs/concepts/features/operations/update/replacing-merge-tree)
* [`FINAL` modifier](https://clickhouse.com/docs/reference/statements/select/from#final-modifier)
* [What is the difference between `OPTIMIZE FINAL` and `FINAL`?](https://clickhouse.com/docs/resources/support-center/knowledge-base/performance-optimization/optimize-final-vs-final)
