ClickHouse delete rows and updates: which method to use

Lightweight DELETE, ALTER TABLE mutations, lightweight UPDATE with patch parts, inserts into ReplacingMergeTree or CollapsingMergeTree, and dropping partitions, each measured on ClickHouse 26.9.

To delete rows in ClickHouse, use DELETE FROM table WHERE ... for occasional row-level deletes, ALTER TABLE ... DROP PARTITION for bulk and retention deletes, and an insert-based engine such as ReplacingMergeTree when rows change all the time. ClickHouse stores data in immutable parts, so there is no cheap in-place delete. Each method chooses a different moment to pay the cost. A lightweight DELETE writes a small hidden mask and leaves the physical cleanup to a later merge. ALTER TABLE ... DELETE is a mutation that rewrites every column of every affected part. Updates follow the same split: ALTER TABLE ... UPDATE rewrites the changed columns, while the newer UPDATE statement writes small patch parts. In our test on 20 million rows, removing one user’s rows with a mutation wrote 459 MiB to disk, and the same lightweight DELETE wrote 95 KiB. Below, we cover how each method works and what it costs. Every statement was run against ClickHouse 26.9.

The five ways to change rows in ClickHouse

MethodStatementWhat it writesGood for
Lightweight deleteDELETE FROM t WHERE ...A hidden _row_exists mask column per affected partOccasional deletes, GDPR requests
Delete mutationALTER TABLE t DELETE WHERE ...A full copy of every affected partRare bulk fixes when space must be freed now
Update mutationALTER TABLE t UPDATE c = ... WHERE ...A new copy of the updated columns in affected partsOne-off backfills and corrections
Lightweight updateUPDATE t SET c = ... WHERE ...Patch parts holding only the changed rows and columnsSmall, frequent corrections (beta)
Insert-based modellingINSERT into ReplacingMergeTree or CollapsingMergeTreeA normal new partRows that change constantly, such as CDC streams
Partition dropALTER TABLE t DROP PARTITION ...Nothing; the part files are removedRetention and whole-month deletes

All the statements work only on MergeTree-family tables. None of them can change a column used in the primary key or partition key. ClickHouse 26.9 refuses that with Cannot UPDATE key column, so a row whose key changes has to be deleted and re-inserted.

Lightweight DELETE: the default way to delete rows

DELETE FROM events WHERE user_id = 42;

According to the DELETE statement reference, a lightweight delete is “implemented as a mutation that marks rows as deleted but does not immediately physically delete them.” It writes a hidden _row_exists column, and only into parts that actually contain matching rows. Every later SELECT filters on that column through PREWHERE. The rows physically disappear the next time a merge rewrites the part. Lightweight deletes became generally available in ClickHouse 23.3.

Three settings and limits shape how it behaves:

  • It waits by default. lightweight_deletes_sync defaults to 2 in 26.9, so the statement returns after every replica has applied the mask. With lightweight_deletes_sync = 0 it returns immediately, and in our test the deleted row was still visible to a SELECT until the background work finished.
  • It refuses tables with projections. On a table with a projection, 26.9 fails with “DELETE query is not allowed … because as it has projections and setting lightweight_mutation_projection_mode is set to THROW”. Set that table setting to drop or rebuild to allow deletes, and accept that the projection gets dropped or rebuilt for the affected parts.
  • It does not free disk space right away. Deleted rows stay on disk until a merge, and nothing schedules that merge. If you must prove that data is physically gone, for example under a data-deletion request, run OPTIMIZE TABLE ... PARTITION ... FINAL on the affected partition. The table setting min_age_to_force_merge_seconds forces merges of old parts, but in our test it did not rewrite a partition that was already a single part. OPTIMIZE ... FINAL did work: it rewrote the parts without the deleted rows and cleared the has_lightweight_delete flag in system.parts.

On a non-replicated MergeTree, add IN PARTITION when you know where the rows are. The docs note that ReplicatedMergeTree tables can prune partitions automatically through optimize_mutations_with_partition_pruning:

DELETE FROM events IN PARTITION 202608 WHERE user_id = 7;

The reference warns that “deleting large volumes of data with the lightweight DELETE statement can negatively affect SELECT query performance”, because every read keeps filtering through the mask until merges catch up. A long mutation queue, many parts and heavy WHERE conditions make it worse. To empty a table, use TRUNCATE TABLE, and for large regular deletes, drop partitions instead.

ALTER TABLE DELETE and UPDATE: what mutations cost

ALTER TABLE events DELETE WHERE user_id = 42;
ALTER TABLE events UPDATE amount = 0 WHERE user_id = 42;

These are mutations. The ALTER reference says mutations on MergeTree tables “execute by rewriting whole data parts”. A delete mutation rewrites every column of every part that holds a matching row. An update mutation rewrites only the updated columns and hard-links the rest, so it is much cheaper than a delete mutation, though still much heavier than a lightweight update. The ALTER UPDATE reference describes the ALTER TABLE prefix as marking “a heavy operation not designed for frequent use.”

Mutations behave differently from ordinary SQL in four ways:

  • They are asynchronous by default. The statement “returns immediately after the mutation entry is added”. Set mutations_sync = 1 to wait on the current server, or 2 to wait on all replicas.
  • They are not atomic. “There is no atomicity - parts are substituted for mutated parts as soon as they are ready”, so a concurrent query can see a mix of old and new values.
  • They cannot be rolled back, only cancelled. Track them in system.mutations and stop a stuck one with KILL MUTATION.
  • They run in order and pile up. Mutations apply one after another, and from 500 unfinished mutations ClickHouse slows new ones down (number_of_mutations_to_delay). At 1,000 it throws “Too many unfinished mutations” (number_of_mutations_to_throw).
-- What is still running, and why it is stuck
SELECT mutation_id, command, parts_to_do, latest_fail_reason
FROM system.mutations
WHERE table = 'events' AND is_done = 0;

-- Cancel it; parts already rewritten stay rewritten
KILL MUTATION WHERE table = 'events' AND mutation_id = 'mutation_2.txt';

The setting apply_mutations_on_fly changes what you see while a mutation is pending. We stopped merges on a small table and ran an ALTER TABLE ... UPDATE. A plain SELECT returned the old value, and the same query with SETTINGS apply_mutations_on_fly = 1 returned the new one. That helps read-after-write consistency, but the default in 26.9 is 0, and each query pays to apply the pending changes.

Lightweight UPDATE: patch parts, beta in 26.9

ClickHouse 25.7 added a standard SQL UPDATE statement, described in the 25.7 release post. It does not rewrite data parts. Instead it writes patch parts, which the UPDATE reference describes as “a special kind of data part that contains only the updated columns and rows.” Queries apply the patches at read time, so the change is visible at once, and later merges write the values into the data parts.

The table needs two settings first. Without them, 26.9 returns “Lightweight updates are supported only for tables with materialized _block_number column”:

CREATE TABLE events
(
    event_id   UInt64,
    user_id    UInt64,
    event_time DateTime,
    event_type LowCardinality(String),
    amount     Decimal(12, 2)
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(event_time)
ORDER BY (event_type, event_time, event_id)
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;

-- Or on an existing table
ALTER TABLE events
    MODIFY SETTING enable_block_number_column = 1, enable_block_offset_column = 1;

UPDATE events SET amount = 0 WHERE user_id = 42;

Know the limits before you build on it:

  • It is still beta. In 26.9, the setting enable_lightweight_update (formerly allow_experimental_lightweight_update) is on by default, but system.settings lists it in the Beta tier.
  • It is sized for small changes. The reference says lightweight updates “are designed to update small amounts of rows (up to about 10% of the table)”. For more than that, use ALTER TABLE ... UPDATE.
  • Frequent tiny updates create parts. Every UPDATE writes new patch parts, and “small updates which are too frequent may lead to a ‘too many parts’ error”. Batch them, for example WHERE id IN (...). The too many parts guide covers that failure mode.
  • Some read optimizations switch off. Skip indexes are not used on columns with pending patches, and projections are not used while the table has any patch parts.

What each method costs: measured on ClickHouse 26.9

We loaded 20 million synthetic event rows into a MergeTree table partitioned by month. That gave four partitions with one part each. Each test started from a freshly merged copy of the table and used mutations_sync = 1, so the statement time includes the rewrite. “Written” is the bytes ClickHouse wrote to disk for the change, from the WriteBufferFromFileDescriptorWriteBytes counter in system.part_log. For the delete mutations it equals the size of the rewritten parts, a full new copy of the table. The machine was a 2-vCPU container, and most figures come from a single run, so treat them as orders of magnitude rather than benchmarks:

StatementRows affectedStatement timeWritten
ALTER TABLE ... DELETE20 (one user)2.1-2.3 s459 MiB
DELETE FROM20 (one user)0.27-0.45 s95 KiB
ALTER TABLE ... DELETE2 million (10%)2.0 s413 MiB
DELETE FROM2 million (10%)0.27 s95 KiB
ALTER TABLE ... UPDATE one column200.79 s58 MiB
UPDATE one column200.15 s11 KiB
ALTER TABLE ... UPDATE one column2 million0.79 s55 MiB
UPDATE one column2 million0.49 s15.7 MiB
ALTER TABLE ... DROP PARTITION5.4 million0.006 s0

Three patterns stand out:

  1. A delete mutation costs about the same whether it removes 20 rows or 2 million. The cost depends on how many parts contain a matching row, not on how many rows match. Our 20 rows were spread across all four partitions, so the whole table was rewritten.
  2. Lightweight methods write almost nothing up front. They move the cost to later reads and merges. The mask for the 10% delete compressed to almost nothing because the deleted rows followed a regular pattern. Real data will compress less well.
  3. Patch size grows with the rows you update. Updating 10% of the table produced a 15.7 MiB patch, which is why the docs set a 10% ceiling.

Reads were barely affected at this scale. An aggregation over the table with 10% of rows masked ran in 0.28-0.32 s, the same as on a table where those rows were simply filtered out. The docs’ warning applies to larger delete volumes, longer mutation queues and many more parts.

Model changes as inserts: ReplacingMergeTree and CollapsingMergeTree

If rows change all the time, as in a CDC feed from an OLTP database, don’t issue a DELETE or UPDATE per change at all. Insert the new state and let the engine resolve it. Inserts are what ClickHouse does best, and the ClickHouse docs point frequent updaters to deduplication-based engines, which change or remove rows “without generating a mutation event”.

ReplacingMergeTree keeps the row with the highest version per sorting key, and its is_deleted column turns an insert into a delete:

CREATE TABLE customers
(
    customer_id UInt64,
    plan        LowCardinality(String),
    mrr         Decimal(10, 2),
    updated_at  DateTime64(6, 'UTC'),
    is_deleted  UInt8 DEFAULT 0
)
ENGINE = ReplacingMergeTree(updated_at, is_deleted)
ORDER BY customer_id;

-- An update and a delete are both just inserts
INSERT INTO customers VALUES (1, 'pro', 199, now64(6), 0);
INSERT INTO customers VALUES (2, 'pro', 199, now64(6), 1);

SELECT count(), sum(mrr) FROM customers FINAL;

The cost moves to read time: until a merge runs, the table holds every version, so queries need FINAL or argMax. Our ReplacingMergeTree guide covers how to choose between them and what each costs, plus how to purge delete rows with CLEANUP.

CollapsingMergeTree cancels rows instead of replacing them. Each row carries an Int8 sign: 1 for a state row, -1 for a cancel row that repeats the old row’s sorting key with the opposite sign. Per the CollapsingMergeTree reference, queries should aggregate with the sign: sum(sign) instead of count(), sum(x * sign) instead of sum(x), and HAVING sum(sign) > 0.

CREATE TABLE orders
(
    order_id UInt64,
    status   LowCardinality(String),
    amount   Decimal(10, 2),
    sign     Int8
)
ENGINE = CollapsingMergeTree(sign)
ORDER BY order_id;

INSERT INTO orders VALUES (1, 'paid', 100, 1), (2, 'paid', 50, 1);
-- Order 1 is refunded: cancel the old state, insert the new one
INSERT INTO orders VALUES (1, 'paid', 100, -1), (1, 'refunded', 100, 1);
-- Order 2 is deleted: cancel it
INSERT INTO orders VALUES (2, 'paid', 50, -1);

SELECT status, sum(sign) AS orders, sum(amount * sign) AS amount
FROM orders
GROUP BY status
HAVING sum(sign) > 0;   -- refunded, 1, 100

A plain count() over that table returned 5 rows. The sign-aware query returned the correct answer: one refunded order. The catch is that your loader must know the old row to cancel it, and the reference warns that an inconsistent change history gives unpredictable results. min and max also cannot be made sign-aware. Use ReplacingMergeTree when the source sends full rows with a version, which is the usual CDC shape. Use CollapsingMergeTree when your pipeline already tracks the previous state and you want sums that stay correct without FINAL.

Drop partitions for bulk and retention deletes

The cheapest delete removes whole parts. If you regularly delete by time, as in “keep 13 months”, partition by month and drop the old partition:

ALTER TABLE events DROP PARTITION 202607;

That took 6 ms for 5.4 million rows in our test, because ClickHouse only removes files. Two cautions apply. First, the partition key has to match the way you delete. A delete by user_id cannot use it, and partitioning too finely causes its own problems, covered in the Postgres to ClickHouse migration playbook. Second, ClickHouse refuses to drop a partition or table larger than 50 GB by default (max_partition_size_to_drop and max_table_size_to_drop in the 26.9 server settings), as a guard against accidents.

For age-based deletes that should happen automatically, a table TTL clause can expire old rows during merges. By default that rewrites parts to remove the expired rows. With the table setting ttl_only_drop_parts = 1, ClickHouse instead drops a part once every row in it has expired, which works best when the TTL lines up with the partition key.

Which method should you use?

SituationUse
A user asks to be deletedDELETE FROM ... WHERE user_id = ..., then force a merge if you must prove physical removal
Old data past retentionPartition by month, DROP PARTITION or a TTL
A one-off correction to a columnALTER TABLE ... UPDATE, or UPDATE if under about 10% of rows
Bad load that must be purged and space freed nowALTER TABLE ... DELETE with mutations_sync = 1, ideally IN PARTITION
Rows mirrored from an OLTP databaseInsert into ReplacingMergeTree with a version and is_deleted
Running totals that must stay correct without FINALCollapsingMergeTree with a sign column
Emptying a tableTRUNCATE TABLE

The rule underneath all of these: a mutation’s cost is set by the number of parts it touches, a lightweight statement’s cost lands later on reads and merges, and an insert-based model puts the cost on every read until merges catch up. Choose the method by where you can afford to pay.

Where Goni fits

Many teams hit this problem because a source database keeps updating and deleting rows that already sit in the warehouse. Goni is one option for handling that without hand-written mutations. Its incremental pipelines from source databases can land late updates and hard deletes in a ReplacingMergeTree target with a version and delete flag. They re-read a configurable look-back window on each run, and they create a current-state view so analysts never write FINAL. The same product runs the ClickHouse warehouse, a YAML semantic layer, data tests, a SQL IDE and dashboards on top. The trade-off is that ClickHouse is the only warehouse Goni queries. You can try it with the 14-day free trial.

FAQ

How do I delete rows in ClickHouse?

Run DELETE FROM table WHERE condition on a MergeTree table. It marks matching rows in a hidden _row_exists column, hides them from queries at once, and removes them physically at the next merge. For large or regular deletes by time, drop partitions instead. ALTER TABLE ... DELETE also works, but it rewrites every affected part.

What is the difference between DELETE and ALTER TABLE DELETE in ClickHouse?

DELETE FROM is a lightweight delete: it writes a small mask and defers the cleanup to merges. ALTER TABLE ... DELETE is a mutation that rewrites all columns of every part containing a matching row. In our 26.9 test, the mutation wrote 459 MiB to remove 20 rows, while the lightweight delete wrote 95 KiB.

Does ClickHouse support UPDATE?

Yes. Since 25.7 there is a standard UPDATE ... SET ... WHERE statement that writes patch parts, still beta in 26.9. It needs the enable_block_number_column and enable_block_offset_column table settings and suits changes to up to about 10% of a table. The older ALTER TABLE ... UPDATE mutation rewrites the updated columns instead.

Why are deleted rows still taking disk space in ClickHouse?

A lightweight delete only masks rows, and they stay on disk until a merge rewrites their part. ClickHouse does not schedule that merge on any fixed timetable. To reclaim space, run OPTIMIZE TABLE ... PARTITION ... FINAL on the affected partition, which rewrites it without the deleted rows, or use DROP PARTITION when whole partitions can go.

How do I check if a ClickHouse mutation is finished?

Query system.mutations for the table and look at is_done, parts_to_do and latest_fail_reason. Mutations run asynchronously by default, so the ALTER statement returns before the work ends. Use mutations_sync = 1 or 2 to wait, and KILL MUTATION to cancel one that is stuck.