Why does a ReplacingMergeTree engine table still return duplicate keys after an update?
An orders table keeps the latest status of each order. Right after a status update the dashboard shows the order twice. Constraints: the table must stay insert-only (no ALTER … UPDATE), and the dashboard query must return exactly one row per order.
CREATE TABLE orders
(
order_id UInt64,
status LowCardinality(String),
updated_at DateTime
)
ENGINE = ReplacingMergeTree(updated_at)
ORDER BY order_id;
INSERT INTO orders VALUES (42, 'created', '2026-11-01 10:00:00');
INSERT INTO orders VALUES (42, 'paid', '2026-11-01 10:05:00');
SELECT order_id, status FROM orders WHERE order_id = 42;
-- 42 created
-- 42 paidFind the cause and fix the read.
Older versions of an ORDER BY key are dropped only when parts merge, at an unknown time; two INSERTs are still two parts. Read with FINAL (a query-time merge, cheaper with a key filter) or argMax by updated_at. OPTIMIZE … FINAL is not a per-query fix.
- Expecting ReplacingMergeTree to deduplicate at insert time
- Running OPTIMIZE … FINAL after inserts as a per-query fix
- Falling back to ALTER UPDATE mutations instead of inserting a new version
- Why does a filter on the
ORDER BYkey makeFINALcheaper? - How would you delete an order from a
ReplacingMergeTreetable without a mutation?
ReplacingMergeTree deduplicates only during a merge, and when that happens is unknown; the docs state outright that the engine does not guarantee the absence of duplicates. Two inserts made two parts, and no merge has combined them yet. Of the versions of one key, a merge keeps the row with the maximum updated_at.
-- Option 1: merge at read time. A filter on the ORDER BY key reads few granules
SELECT order_id, status
FROM orders FINAL
WHERE order_id = 42;
-- Option 2: resolve versions with an aggregate
SELECT order_id, argMax(status, updated_at) AS status
FROM orders
WHERE order_id = 42
GROUP BY order_id;OPTIMIZE TABLE orders FINAL rewrites parts and is heavy on a large table; besides, the next insert brings the duplicate back until the next merge. This model — inserting a new version of a row instead of ALTER … UPDATE — is how ClickHouse changes data without mutations; the price is resolving versions at read time.