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.
Find the running merge
The merge started byOPTIMIZE is listed in system.merges together with the background merges:
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:OPTIMIZE gets this error, and system.merges no longer shows the merge:
OPTIMIZE. If system.part_log is enabled, the aborted merge is recorded there:
OPTIMIZE ... FINAL that was aborted is not resumed.
Why cancelling the query is not enough
A merge that is in progress is not interrupted when theOPTIMIZE 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:
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 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
ForReplicatedMergeTree 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. 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:
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 marksSYSTEM 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 and What is the difference between OPTIMIZE FINAL and FINAL?.