ClickHouse ReplacingMergeTree: dedup, FINAL and argMax
Why duplicate rows survive until a merge, how the version and is_deleted columns pick a winner, and what FINAL, argMax and LIMIT 1 BY each cost at read time.
ClickHouse ReplacingMergeTree still returns duplicate rows because it deduplicates only when a background merge combines the parts that hold them, and nothing schedules that merge. Every INSERT writes a new immutable part. When ClickHouse later merges parts, it keeps one row per sorting key: the one with the highest version, or the last one inserted if there is no version column. Until then, a plain SELECT reads every version, and a count() or sum() over the table is wrong. The ReplacingMergeTree reference says this directly: deduplication “occurs only during a merge” and the engine “does not guarantee the absence of duplicates”. You have two ways to get correct numbers. You can deduplicate at read time with FINAL, argMax or LIMIT 1 BY, or you can read from a model that has already been deduplicated. Below, we cover how the engine picks the surviving row and what each read-time method costs. We also cover four mistakes that return wrong numbers even when you think you have deduplicated. Every query here was run against ClickHouse 26.9.
Why does ReplacingMergeTree still show duplicate rows?
Here is a small customer table with a version column (updated_at) and a delete flag. Three separate inserts write three parts:
CREATE TABLE customers
(
customer_id UInt64,
plan LowCardinality(String),
mrr Decimal(10, 2),
updated_at DateTime64(3, 'UTC'),
is_deleted UInt8 DEFAULT 0
)
ENGINE = ReplacingMergeTree(updated_at, is_deleted)
ORDER BY customer_id;
INSERT INTO customers VALUES
(1, 'starter', 49, '2026-10-01 09:00:00', 0),
(2, 'pro', 199, '2026-10-01 09:00:00', 0);
-- customer 1 upgrades
INSERT INTO customers VALUES (1, 'pro', 199, '2026-10-05 14:30:00', 0);
-- customer 2 is deleted in the source system
INSERT INTO customers VALUES (2, 'pro', 199, '2026-10-07 08:00:00', 1);
A plain read returns all four rows, and the totals are wrong:
SELECT count(), sum(mrr) FROM customers; -- 4, 646
SELECT count(), sum(mrr) FROM customers FINAL; -- 1, 199
The correct answer is one live customer paying 199. Without FINAL, the query counts customer 1 twice and still counts customer 2, who was deleted.
Parts are merged in the background, at a time ClickHouse picks. Its ReplacingMergeTree guide warns that merges don’t guarantee deduplication “and you shouldn’t rely on it”. On a busy table, new duplicates arrive faster than merges remove them. On a quiet table, the last few parts can sit unmerged for a long time. Large parts can also stop merging altogether: once a part reaches max_bytes_to_merge_at_max_space_in_pool, it is no longer picked for merges, so duplicates spread across two large parts can last indefinitely.
How does ReplacingMergeTree decide which row wins?
The engine signature is ReplacingMergeTree([ver [, is_deleted]]). When rows share the same ORDER BY value, a merge keeps one of them according to these rules:
| Table definition | Row that survives a merge |
|---|---|
No ver | The last inserted row |
ver set | The row with the highest ver |
ver set, versions tied | The last inserted row among the tied ones |
ver and is_deleted set, winner has is_deleted = 1 | The delete row itself, which FINAL then hides |
ver can be any UInt*, Date, DateTime or DateTime64 column. is_deleted must be UInt8, and it can only be used together with ver. Use a version that increases on every change to the source row, such as a database log position, a Kafka offset or a microsecond updated_at. A timestamp with one-second resolution produces ties, and ties fall back to insert order. That fallback is fine for a single loader that writes in order, but it is unsafe for parallel loaders or backfills.
Two other rules decide which rows count as duplicates in the first place:
- The sorting key defines uniqueness, not the primary key. In the reference’s words, “uniqueness of rows is determined by the
ORDER BYtable section, notPRIMARY KEY”. EveryORDER BYcolumn must therefore be immutable for a given entity. Ifplanwere in the sort key, an upgrade would create a second row that never merges with the first. - Merges never cross partitions. If the partition key can change for a row, its versions end up in different partitions and are never merged. We show the effect on
FINALbelow.
Row deduplication vs insert deduplication
People searching “ClickHouse duplicate rows” often mean a different mechanism. Insert deduplication drops a repeated insert block, typically a retry after a timeout, by checking a hash of the block. It applies only to blocks that are identical, and it comes with defaults that differ by table type. In 26.9, a Replicated table remembers the last 10,000 blocks (replicated_deduplication_window) for up to an hour. A non-replicated MergeTree has non_replicated_deduplication_window = 0, so it does not deduplicate inserts at all. You can pass your own insert_deduplication_token per insert to make retries safe; on a non-replicated table, that works only after you set a deduplication window. None of this touches two different rows for the same key, which is ReplacingMergeTree’s job. Most pipelines need both.
FINAL vs argMax vs LIMIT 1 BY: three ways to read the latest row
FINAL tells ClickHouse to apply the merge logic while it reads. It honours ver, ties and is_deleted exactly as a merge would, and it applies to the ReplacingMergeTree, Summing, Aggregating, Collapsing and VersionedCollapsing engines.
SELECT plan, count() AS customers, sum(mrr) AS mrr
FROM customers FINAL
GROUP BY plan;
-- Or apply FINAL to every eligible table in the query, joins and subqueries included
SELECT plan, count(), sum(mrr) FROM customers GROUP BY plan
SETTINGS final = 1;
Per the FROM clause docs, FINAL queries run in parallel up to max_final_threads, and they may read primary-key columns you did not select. If the table has an alias, FINAL comes after it (FROM customers AS c FINAL).
argMax with GROUP BY rebuilds the latest row yourself. Each non-key column needs its own argMax(column, version), and the delete filter goes in HAVING, after the winner has been chosen:
SELECT plan, count() AS customers, sum(mrr) AS mrr
FROM
(
SELECT
customer_id,
argMax(plan, updated_at) AS plan,
argMax(mrr, updated_at) AS mrr
FROM customers
GROUP BY customer_id
HAVING argMax(is_deleted, updated_at) = 0
)
GROUP BY plan;
This works on any engine, including a plain MergeTree that holds a change log, and it is explicit about what “latest” means. It is also verbose, and the inner query must name every column.
LIMIT 1 BY sorts and keeps the first row per key:
SELECT *
FROM customers
ORDER BY customer_id, updated_at DESC
LIMIT 1 BY customer_id;
It reads naturally for point lookups and small tables. It does not handle is_deleted (filter afterwards in an outer query), and sorting the whole table to keep one row per key is expensive at scale.
What each read-time method costs
Advice about cost has shifted over the years. Many older posts call argMax the cheaper option. We measured both on ClickHouse 26.9 in a 2-vCPU container. The test table had 14.8 million rows across 14 unmerged parts and 10 million distinct customers, with about 43% of them updated and 1.4% of them deleted. Each query computed customers and MRR per plan, and each figure is the median of three runs:
| Query | Rows read | Time | Peak memory | Correct? |
|---|---|---|---|---|
Plain GROUP BY, no dedup | 14.8M | 0.06 s | 2 MiB | No: 4.9M rows too many |
FROM ... FINAL | 14.8M | 0.61 s | 47 MiB | Yes |
argMax subquery + HAVING | 14.8M | 1.60 s | 790 MiB | Yes |
FINAL with WHERE customer_id = ... | 24,576 | 0.004 s | under 1 MiB | Yes |
argMax with WHERE customer_id = ... | 24,576 | 0.004 s | about 1 MiB | Yes |
This is one synthetic table on a small machine, so test your own data before relying on these figures. Still, the shape matches how the two methods work. FINAL takes advantage of the fact that each part is already sorted by the key, so it can merge the parts as a stream. argMax builds a hash table with one entry per key, so its memory grows with the number of keys. The FINAL clause docs now describe the overhead as slight and suggest aggregating instead where possible, for example by discarding duplicates in the query. Both methods are cheap when the WHERE clause filters on leading sort-key columns, because ClickHouse skips most granules before any deduplication happens.
The best ways to make FINAL cheaper:
- Filter on sort-key columns or skip indexes. Sort-key filters prune data before the merge step, and since 25.6 skip indexes do too (
use_skip_indexes_if_finalanduse_skip_indexes_if_final_exact_modedefault to 1, so results stay correct). - Partition by an immutable column and set
do_not_merge_across_partitions_select_final = 1. Each partition is then deduplicated on its own and in parallel. In the official guide, partitioning by year cut an example query from about 2.3 s to 1.0 s. From 23.12, ClickHouse skips cross-partition merging automatically when the partition key is a prefix of the sort key. - Let merges keep up. The fewer overlapping parts there are, the less work
FINALhas to do. Batched inserts help, as covered in the too many parts guide.
Four mistakes that return wrong numbers
1. Filtering before you deduplicate
A WHERE on a non-key column, placed in the same query as the argMax and before it runs, filters the history instead of the current state. Customer 1 was on starter and is now on pro:
-- Wrong: finds customer 1, because an old version matched
SELECT count() FROM (
SELECT customer_id FROM customers
WHERE plan = 'starter'
GROUP BY customer_id
); -- 1
-- Right: pick the latest version first, then filter
SELECT count() FROM (
SELECT customer_id, argMax(plan, updated_at) AS plan
FROM customers GROUP BY customer_id
) WHERE plan = 'starter'; -- 0
SELECT count() FROM customers FINAL WHERE plan = 'starter' returns the correct 0. In 26.9, optimize_move_to_prewhere_if_final is off by default, so a WHERE runs after the merge step.
2. Writing PREWHERE by hand on a FINAL query
An explicit PREWHERE runs while the data is read, before FINAL picks the winners. SELECT count() FROM customers FINAL PREWHERE plan = 'starter' returned 1 in our test, which is the same mistake as the first one. Use PREWHERE with FINAL only on sort-key columns.
3. Assuming argMax breaks ties the way FINAL does
We inserted a third row for customer 1 with the same updated_at as the second. FINAL returned the last inserted row (enterprise), as the engine rules require. argMax(plan, updated_at) returned pro. The argMax docs say that when several rows share the maximum, which value comes back “is not deterministic”. If ties are possible, use a strictly increasing version, or switch to a tuple version such as argMax(plan, (updated_at, load_seq)).
4. Partitioning on a column that changes
We partitioned a table by toYYYYMM(updated_at) and wrote two versions of one customer, one in September and one in October:
- Default
FINALreturned one row, because it merged across partitions. - With
do_not_merge_across_partitions_select_final = 1, it returned both rows. OPTIMIZE TABLE ... FINALalso left both rows in place, because merges never compare rows from different partitions.
Partition by something that never changes for an entity, such as the creation month, or don’t partition at all. The Postgres to ClickHouse migration playbook applies the same rule to its schema design.
How do you remove deleted rows for good?
is_deleted = 1 hides a row from FINAL, but the merge keeps the delete row, so it still takes up disk space. The reason is safety: if an older version of that key arrives later, the delete row still beats it. To drop delete rows physically, enable the experimental table setting allow_experimental_replacing_merge_with_cleanup, then use one of two options:
- Run
OPTIMIZE TABLE customers FINAL CLEANUP, optionally limited to one partition. - Set
enable_replacing_merge_with_cleanup_for_min_age_to_force_mergetogether withmin_age_to_force_merge_secondsandmin_age_to_force_merge_on_partition_only, so that old partitions are cleaned in the background.
That safety goes away after a cleanup. We deleted customer 2, ran a cleanup, and then inserted a late row for customer 2 with an older version than the delete. FINAL returned the customer again, because the delete row that would have won was gone. Run cleanup only on partitions that can no longer receive late rows. The guide adds two more conditions: run SYSTEM SYNC REPLICA first on replicated tables, and use soft deletes only for tables where fewer than about 10% of rows are deleted, unless cleanup is scheduled.
OPTIMIZE ... FINAL without CLEANUP is not a substitute for reading with FINAL. It rewrites whole partitions, it is “memory-intensive on large tables” according to the guide, and the next insert creates duplicates again.
A ReplacingMergeTree playbook
- Sort key = immutable filter columns, ending with the source primary key. Nothing in
ORDER BYorPARTITION BYmay change for an entity. - Use a strictly increasing version. Prefer a log position or sequence over a wall-clock time, and take it from the source, not from
now()at load time. - Add
is_deletedif the source deletes rows, and send deletes as tombstones with a newer version. The CDC to ClickHouse comparison covers the tombstone pattern for CDC deletes. - Read with
FINALby default. Wrap it in a view (CREATE VIEW customers_current AS SELECT * FROM customers FINAL WHERE ...) so dashboard authors never query the raw table. - Use
argMaxwhen you need the logic in SQL, for example over an append-only change log or when building a model. Always filter after the winner has been chosen. - Build a deduplicated model when
FINALis still too slow. A scheduled rebuild of a current-state table moves the cost from every dashboard query to one refresh. - Test for duplicates. A
GROUP BY key HAVING count() > 1check on the view, not the raw table, catches a broken sort key early.
Where Goni fits
If you would rather not maintain these patterns in every pipeline, Goni is one option. Its incremental pipelines can land late updates and hard deletes from source databases in a ReplacingMergeTree target. They re-read a configurable look-back window on each run and create a current-state view, so analysts and dashboards 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
Does ReplacingMergeTree guarantee unique rows?
No. It removes duplicates only when a background merge combines the parts that hold them, and ClickHouse does not promise when, or whether, that merge happens. Rows in different partitions are never merged. To get unique results, deduplicate at read time with FINAL or argMax, or query a view or model that does it for you.
Is FINAL slow in ClickHouse?
Less than it used to be. FINAL runs in parallel, and on our 26.9 test it took about ten times as long as a plain aggregation over 14.8 million rows, while still beating argMax in both time and memory. It costs most on wide scans without sort-key filters. Filtering on key columns and partitioning by an immutable column reduce the cost the most.
Should I use FINAL or argMax?
Use FINAL on ReplacingMergeTree tables. It follows the engine’s exact rules for versions, ties and deletes, and in our test it used far less memory. Use argMax when the table is not a ReplacingMergeTree, when you need the logic written out in SQL, or when you build a model. In both cases, filter on non-key columns only after deduplication.
How do I force ClickHouse to remove duplicates now?
OPTIMIZE TABLE t FINAL merges each partition into one part and removes duplicates, but it rewrites all the data, uses a lot of memory on large tables, and the next insert brings duplicates back. It is fine for a one-off fix or a small table. For everyday correctness, read with FINAL or through a deduplicated view.
How do I delete rows in a ReplacingMergeTree?
Declare the table with ReplacingMergeTree(ver, is_deleted) and insert a copy of the row with is_deleted = 1 and a higher version. FINAL then hides it. The delete row stays on disk until a CLEANUP merge, which needs the experimental allow_experimental_replacing_merge_with_cleanup table setting. Run cleanup only where older versions can no longer arrive.