Overview
ClickHouse has no unique constraints or in-place updates. To represent “latest version of a row” you insert a new version and let a special engine remove old versions during background merges. Until a merge happens, duplicates are visible.
Core concepts
ReplacingMergeTree([version]): rows with the sameORDER BYkey collapse to one (the highestversion, or the last inserted). Merges do this, at an unpredictable time, only inside a partition.CollapsingMergeTree(sign)andVersionedCollapsingMergeTree: pairs of rows withsign = +1and-1cancel out; they allow deletes and updates in streams but require correct pairs.SummingMergeTreeandAggregatingMergeTreecombine numeric rows or aggregate states (ch-materialized-views).- Reading the latest row without waiting for merges:
SELECT ... FROM t FINALmerges at query time (parallel in recent versions, but costly on big tables).argMax(col, version) ... GROUP BY keypicks the latest version explicitly; often cheaper and always correct.is_deletedcolumn withReplacingMergeTree(version, is_deleted)marks deletions.
Worked example
CREATE TABLE users_r (id UInt32, name String, version UInt32) ENGINE = ReplacingMergeTree(version) ORDER BY id;
SYSTEM STOP MERGES users_r;
INSERT INTO users_r VALUES (1,'Ana',1),(2,'Bao',1);
INSERT INTO users_r VALUES (1,'Ana Nguyen',2);| Query | Result |
|---|---|
SELECT * FROM users_r | 3 rows: Ana v1, Ana Nguyen v2, Bao v1 |
SELECT * FROM users_r FINAL | 2 rows: Ana Nguyen, Bao |
SELECT id, argMax(name, version) FROM users_r GROUP BY id | 2 rows: Ana Nguyen, Bao |
after SYSTEM START MERGES and OPTIMIZE ... FINAL | 2 rows stored |
Pitfalls and production notes
- Never assume uniqueness without
FINALorargMax; dashboards counting rows can double count. - Deduplication only happens within one partition and one shard; the ORDER BY key defines identity, so choose it to match the business key (and not include the version).
FINALon very large tables is slow; reduce the scanned range with the primary key and partition filters.- Frequent updates of the same row create many versions and extra merge work; ClickHouse is not an OLTP store (ch-when-not-to-use). Lightweight updates and deletes exist for occasional corrections (ch-mutations).
- Distributed setups need all versions of a key on the same shard (shard by the key).
Practice questions
- Why can
count()over a ReplacingMergeTree table be wrong? - When is
argMaxbetter thanFINAL? - How does
CollapsingMergeTreerepresent a deleted row?
References
- ClickHouse documentation, ReplacingMergeTree; CollapsingMergeTree
Related
ch-mutations · ch-materialized-views · ch-mergetree-parts · ch-when-not-to-use