> ## 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 do I stop a running OPTIMIZE FINAL?

> How to abort the merge started by OPTIMIZE TABLE ... FINAL with SYSTEM STOP MERGES, why cancelling the query does not stop it, and what is different for replicated tables.

On a non-replicated `MergeTree` table, run `SYSTEM STOP MERGES` for the table. It aborts the merges that are running on the table, including the one started by `OPTIMIZE TABLE ... FINAL`. When the `OPTIMIZE` query has returned its error, run `SYSTEM START MERGES` to allow background merges again. Cancelling the `OPTIMIZE` query itself does not stop the merge.

```sql theme={null}
SYSTEM STOP MERGES db.events;

-- after the OPTIMIZE query has returned "Cancelled merging parts":
SYSTEM START MERGES db.events;
```

On a replicated table the merge can only be paused this way, see [Replicated tables](#replicated-tables).

## Find the running merge

The merge started by `OPTIMIZE` is listed in [`system.merges`](https://clickhouse.com/docs/reference/system-tables/merges) together with the background merges:

```sql theme={null}
SELECT
    database,
    table,
    round(elapsed) AS elapsed_s,
    round(progress, 2) AS progress,
    num_parts,
    result_part_name,
    formatReadableSize(total_size_bytes_compressed) AS size
FROM system.merges
WHERE NOT is_mutation;
```

`progress` goes from 0 to 1, and `num_parts` is the number of source parts. A merge of a whole partition by `OPTIMIZE ... FINAL` is usually the one with the largest `size`.

## Non-replicated MergeTree tables

From another session, stop the merges of the table:

```sql theme={null}
SYSTEM STOP MERGES db.events;
```

The session that runs `OPTIMIZE` gets this error, and `system.merges` no longer shows the merge:

```text theme={null}
Code: 236. DB::Exception: Cancelled merging parts: While executing MergeTreeSequentialSource. (ABORTED)
```

The source parts stay active, so no data is lost and the table is in the same state as before the `OPTIMIZE`. If [`system.part_log`](https://clickhouse.com/docs/reference/system-tables/part_log) is enabled, the aborted merge is recorded there:

```sql theme={null}
SELECT
    event_type,
    part_name,
    length(merged_from) AS source_parts,
    errorCodeToName(error) AS error_name
FROM system.part_log
WHERE database = 'db' AND table = 'events' AND event_type = 'MergeParts'
ORDER BY event_time_microseconds DESC
LIMIT 1;
```

```text theme={null}
   ┌─event_type─┬─part_name──┬─source_parts─┬─error_name─┐
1. │ MergeParts │ all_1_12_1 │           12 │ ABORTED    │
   └────────────┴────────────┴──────────────┴────────────┘
```

Then allow merges again:

```sql theme={null}
SYSTEM START MERGES db.events;
```

Background merges resume and pick parts by the usual rules. The `OPTIMIZE ... FINAL` that was aborted is not resumed.

> [!WARNING]
>
> Do not leave merges stopped. While they are stopped for a table:
>
> * no background merges run, so every `INSERT` adds parts that stay unmerged;
> * mutations of the table (`ALTER TABLE ... UPDATE`, `ALTER TABLE ... DELETE`) wait;
> * any new `OPTIMIZE` of the table fails at once with `Cancelled merging parts. (ABORTED)`.
>
> `SYSTEM STOP MERGES` without a table name stops merges for all `MergeTree` tables. The stopped state is kept in memory only: after a server restart, merges run again.

## Why cancelling the query is not enough

A merge that is in progress is not interrupted when the `OPTIMIZE` query is cancelled. The merge runs to the end, the merged part replaces the source parts, and only then the statement returns an error. You can see this with a query time limit on a table whose merge takes longer than the limit:

```sql theme={null}
OPTIMIZE TABLE db.events FINAL SETTINGS max_execution_time = 1;
```

```text theme={null}
Code: 159. DB::Exception: Timeout exceeded: maximum: 1000.000 ms. (TIMEOUT_EXCEEDED)
```

The statement fails, but only after the merge has finished: `system.part_log` shows a `MergeParts` event without an error that took longer than the limit, and the partition consists of one part. [`KILL QUERY`](https://clickhouse.com/docs/reference/statements/kill#kill-query) behaves the same way: the merge continues, and when it has finished, the `OPTIMIZE` statement returns the error `QUERY_WAS_CANCELLED`. Use `SYSTEM STOP MERGES` when you need the merge itself to stop.

## Replicated tables

For `ReplicatedMergeTree` tables, `OPTIMIZE` does not merge anything itself. It writes a merge task to the replication log, every replica puts the task into its replication queue and runs it in the background, and the `OPTIMIZE` query waits for the result according to [`alter_sync`](https://clickhouse.com/docs/reference/settings/session-settings/alter#alter_sync). Killing the `OPTIMIZE` query therefore only ends the wait.

`SYSTEM STOP MERGES` aborts the running merge on the replica where you execute it (add `ON CLUSTER` to run it on all replicas), but the task stays in the queue and starts again from the beginning after `SYSTEM START MERGES`. While merges are stopped you can see the task waiting in [`system.replication_queue`](https://clickhouse.com/docs/reference/system-tables/replication_queue):

```sql theme={null}
SELECT
    database,
    table,
    type,
    new_part_name,
    is_currently_executing,
    num_postponed,
    postpone_reason
FROM system.replication_queue
WHERE type = 'MERGE_PARTS';
```

The `postpone_reason` of a paused task says that the entry is not executed `because merges and mutations are cancelled now`. So on a replicated table you can postpone the merge to a quieter time, but not cancel it.

## ClickHouse Cloud

The reference marks [`SYSTEM STOP MERGES`](https://clickhouse.com/docs/reference/statements/system#stop-merges) and `SYSTEM START MERGES` as not supported in ClickHouse Cloud. If a manual `OPTIMIZE ... FINAL` causes problems for a ClickHouse Cloud service, contact ClickHouse support.

## Avoid the situation

`OPTIMIZE ... FINAL` rewrites every part of the table, regardless of size. If you need it at all, limit it to one partition with `OPTIMIZE TABLE db.events PARTITION ... FINAL`. See [Avoid `OPTIMIZE FINAL`](https://clickhouse.com/docs/concepts/best-practices/avoid-optimize-final) and [What is the difference between `OPTIMIZE FINAL` and `FINAL`?](https://clickhouse.com/docs/resources/support-center/knowledge-base/performance-optimization/optimize-final-vs-final).
