Overview
PARTITION BY splits a MergeTree table into logical partitions. In ClickHouse partitions exist mainly for data management (drop, move, detach or back up whole partitions, TTL), not for query speed; the sorting key does the pruning (ch-sorting-key-sparse-index). Compare table-partitioning.
Core concepts
- Common key:
toYYYYMM(event_time)ortoDate(...). A part never spans partitions, and merges only combine parts of the same partition. - Partition pruning uses the partition expression and per-part min-max values of the key columns.
- Operations on whole partitions are metadata-fast:
ALTER TABLE ... DROP PARTITION 'p',DETACH,ATTACH,MOVE PARTITION TO TABLE,FREEZE. - Few, large partitions: aim for tens or hundreds in total. Too many partitions means too many parts, slow startup and many small merges.
max_partitions_per_insert_block(100 by default) limits how many partitions one insert may touch.
Worked example
Five million rows spread over one year (event_time = start + number*6 s), partitioned by month:
CREATE TABLE events_p (event_time DateTime, user_id UInt32, country LowCardinality(String), amount Float64)
ENGINE = MergeTree PARTITION BY toYYYYMM(event_time) ORDER BY (country, user_id);After OPTIMIZE ... FINAL there was one part per partition (12 partitions of about 5 MiB each). The query for March read 446,400 rows (one month); a query without any time filter read 1,321,792 rows because the sorting key helped with country='VN'. EXPLAIN indexes=1 showed:
Min-Max Parts: 1/12 Granules: 55/610
Partition Parts: 1/1 Granules: 55/55Dropping a month is instant:
ALTER TABLE events_p DROP PARTITION '202501'; -- 4,553,600 rows left, earliest 2025-02-01Pitfalls and production notes
- Do not partition by a high-cardinality column (user id): that creates millions of parts.
- Partition by month or day for retention-based deletes; for TTL use ch-ttl-tiered-storage.
- Queries should still filter on the sorting key; do not rely on partitions to speed them up.
- Changing the partition expression requires creating a new table and copying data.
- A partition is the unit of backup granularity too (ch-backup-restore).
Practice questions
- Why does partitioning not replace a good sorting key in ClickHouse?
- How would you retain 90 days of data with daily partitions?
- What limit protects you from an insert touching thousands of partitions?
References
- ClickHouse documentation, Custom partitioning key
Related
table-partitioning · ch-ttl-tiered-storage · ch-mergetree-parts · sqlserver-partitioning · oracle-partitioning