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 same ORDER BY key collapse to one (the highest version, or the last inserted). Merges do this, at an unpredictable time, only inside a partition.
  • CollapsingMergeTree(sign) and VersionedCollapsingMergeTree: pairs of rows with sign = +1 and -1 cancel out; they allow deletes and updates in streams but require correct pairs.
  • SummingMergeTree and AggregatingMergeTree combine numeric rows or aggregate states (ch-materialized-views).
  • Reading the latest row without waiting for merges:
    • SELECT ... FROM t FINAL merges at query time (parallel in recent versions, but costly on big tables).
    • argMax(col, version) ... GROUP BY key picks the latest version explicitly; often cheaper and always correct.
    • is_deleted column with ReplacingMergeTree(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);
QueryResult
SELECT * FROM users_r3 rows: Ana v1, Ana Nguyen v2, Bao v1
SELECT * FROM users_r FINAL2 rows: Ana Nguyen, Bao
SELECT id, argMax(name, version) FROM users_r GROUP BY id2 rows: Ana Nguyen, Bao
after SYSTEM START MERGES and OPTIMIZE ... FINAL2 rows stored

Pitfalls and production notes

  • Never assume uniqueness without FINAL or argMax; 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).
  • FINAL on 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

  1. Why can count() over a ReplacingMergeTree table be wrong?
  2. When is argMax better than FINAL?
  3. How does CollapsingMergeTree represent a deleted row?

References

  • ClickHouse documentation, ReplacingMergeTree; CollapsingMergeTree

ch-mutations · ch-materialized-views · ch-mergetree-parts · ch-when-not-to-use