A ReplacingMergeTree partitioned by toYYYYMM(updated_at) keeps some keys duplicated forever — why?
Merges only combine parts of one partition, so once an update moves a key to a new month its two versions never collapse on disk, OPTIMIZE … FINAL included. SELECT … FINAL still reconciles them by default, at query-time cost. Partition by an immutable column.
- Believing OPTIMIZE … FINAL collapses duplicates across partitions
- Assuming SELECT … FINAL also stops at partition boundaries by default
- Partitioning a ReplacingMergeTree by a column that changes on every update
- When does
do_not_merge_across_partitions_select_finalmakeFINALcheaper yet still correct? - How would you find keys that already have versions in several partitions?
The partitioning-key docs: "A merge only works for data parts that have the same value for the partitioning expression." The row for order 42 inserted in October sits in partition 202610; its new version with a November updated_at sits in 202611. Background merges and OPTIMIZE … FINAL work inside a partition, so both versions stay in storage forever. A plain SELECT, count() and every materialized view see both.
-- Bad: a key's version "moves" to another partition
CREATE TABLE orders_bad
(
order_id UInt64,
status LowCardinality(String),
created_at DateTime,
updated_at DateTime
)
ENGINE = ReplacingMergeTree(updated_at)
PARTITION BY toYYYYMM(updated_at)
ORDER BY order_id;
-- Good: created_at never changes, so all versions of an order share a partition
CREATE TABLE orders
(
order_id UInt64,
status LowCardinality(String),
created_at DateTime,
updated_at DateTime
)
ENGINE = ReplacingMergeTree(updated_at)
PARTITION BY toYYYYMM(created_at)
ORDER BY (created_at, order_id);SELECT … FINAL behaves differently: do_not_merge_across_partitions_select_final is off by default, so FINAL reconciles versions across partitions too — correct, but costlier. Skipping the cross-partition merge is safe only when every partition-key column is in the primary key: then one key cannot span two partitions, and ClickHouse applies the optimisation itself (enable_automatic_decision_for_merging_across_partitions_for_final).