ClickHouse PARTITION BY: best practices and limits
Partitions are for dropping, replacing and expiring data, not for speed. How to pick the key, month or day, the limits a bad key hits, and when to skip it, tested on ClickHouse 26.10.
The best ClickHouse PARTITION BY for most tables is a monthly key on the event time, such as toYYYYMM(ts), or no partition key at all. ClickHouse’s own best-practice guide calls partitioning “primarily a data management technique and not a query optimization tool”: a partition exists so you can drop, replace, move or expire a slice of data in one cheap metadata operation. Fast filtering comes from the ORDER BY key. Partitions also have a cost. Every insert writes at least one part per partition it touches, parts never merge across partitions, and a query that spans many partitions opens many more parts. In our test on 30 million rows, a daily partition key made a single-tenant query read 146 times more rows than the same table with no partition key, and a 365-day backfill was refused outright. Below: what partitions do, how to pick the key, month or day, the limits a bad key hits, and when to skip partitioning. Every statement was run against ClickHouse 26.10.
What does PARTITION BY do in ClickHouse?
PARTITION BY takes any expression over the table’s columns. Each distinct value of that expression is a partition, and ClickHouse keeps the data parts of each partition separate:
CREATE TABLE events
(
tenant_id UInt32,
ts DateTime,
event_type LowCardinality(String),
amount Decimal(12, 2)
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, ts);
Four consequences follow, and every best practice below comes from one of them.
- An insert is split by partition. A block of rows covering three months becomes three new parts, one per month, each sorted by the
ORDER BYkey. - Merges stay inside a partition. Two parts from different months are never merged, so the partition count sets a floor on the part count.
- Each part keeps a MinMax index on the columns used in the partition expression, here
ts. The query planner uses it to skip whole parts before it looks at the primary index. - A partition is the unit of bulk operations.
DROP,DETACH,REPLACE,MOVEand TTL part drops all work on whole partitions or parts, without rewriting rows.
You can see the partitions in system.parts. The partition ID is readable for integer and date keys and a hash for strings:
SELECT partition, partition_id, name, rows
FROM system.parts
WHERE table = 'events' AND active
ORDER BY partition DESC
LIMIT 3;
| Partition expression | partition | partition_id |
|---|---|---|
toYYYYMM(ts) | 202609 | 202609 |
toDate(ts) | 2026-10-31 | 20261031 |
event_type (a String) | purchase | abc50385606e71cf1a0791544ec188d6 |
no PARTITION BY | tuple() | all |
A table without a partition key is one partition called all. That is a normal, healthy layout, not a missing setting.
Does partitioning make ClickHouse queries faster?
Usually not, and a fine-grained key makes them slower. We loaded the same 30 million rows (1,000 tenants, two years of events, November 2024 to October 2026) into three tables that differ only in PARTITION BY. All three use ORDER BY (tenant_id, ts) and the same LZ4 codec, and each was compacted with OPTIMIZE TABLE ... FINAL so every partition holds one part. The rows-read numbers come from the query summary; times are the median of five runs on one machine and will differ on yours.
| No partition key | toYYYYMM(ts) | toDate(ts) | |
|---|---|---|---|
| Active parts | 1 | 24 | 730 |
| Files on disk in active parts | 19 | 504 | 9,490 |
| One tenant, one month | 8,192 rows, 4 ms | 8,192 rows, 4 ms | 245,760 rows, 14 ms |
| One tenant, all time | 40,960 rows, 4 ms | 212,992 rows, 9 ms | 5,980,160 rows, 74 ms |
| Ten tenants, all time | 311,296 rows, 6 ms | 393,216 rows, 8 ms | 5,980,160 rows, 64 ms |
| All tenants, one month | 9,461,760 rows, 58 ms | 1,232,877 rows, 10 ms | 1,232,877 rows, 19 ms |
| Full scan, grouped by month | 30,000,000 rows, 84 ms | 30,000,000 rows, 72 ms | 30,000,000 rows, 125 ms |
Three patterns show up.
Queries on the sort-key prefix do not need partitions. Filtering by tenant_id is fast on the unpartitioned table because the primary index already narrows the read to a few granules. Partitioning splits that tenant’s rows into one slice per partition, and each slice costs at least one granule (8,192 rows) to read. With 730 daily partitions, one tenant’s 30,000 rows cost 730 granules.
Partitions help when you filter on a column that is not the sort-key prefix. “All tenants, one month” filters on ts, the second column of the sort key, so the primary index on the unpartitioned table can skip little and reads almost a third of the table. The monthly table skips 23 of 24 parts by the MinMax index and reads exactly one month. The ClickHouse docs name this as the case where partitioning can help: a query filters on the partition column, and that column is not part of the primary key. A column deep in the key, like ts here, behaves much the same. EXPLAIN indexes = 1 shows the pruning:
└──ReadFromMergeTree (default.events_month)
...
Indexes:
Min-Max
Keys:
ts
Condition: and((ts in (-Inf, 1790812799]), (ts in [1788220800, +Inf)))
Parts: 1/24
Granules: 151/3674
Partition
Keys:
toYYYYMM(ts)
Condition: and((toYYYYMM(ts) in (-Inf, 202609]), (toYYYYMM(ts) in [202609, +Inf)))
Parts: 1/1
Granules: 151/151
PrimaryKey
...
Many small partitions are slower everywhere. The daily table was the slowest on every query except the one-month filter, where it tied on rows read and still took twice as long. Its 730 parts averaged about 370 KiB, small enough that ClickHouse stored them as Compact parts (anything under min_bytes_for_wide_part, 10 MiB by default).
If the “all tenants, one month” query matters to you and the table has no other reason to be partitioned, a projection sorted by time is the alternative. Our guide to choosing the ORDER BY and primary key covers that trade-off.
How to choose a ClickHouse partition key
Pick the key from how data leaves or is rewritten, not from how it is queried. Four questions settle it:
- What do you delete, expire, archive or reload as a unit? If old data is dropped by month, partition by month. If nothing is ever removed by time, you may not need a partition key.
- How many partitions will exist over the retention period? The best-practice guide says a key with “fewer than 100 - 1,000 distinct values” is usually optimal. Multiply retention by granularity and check.
- How many partitions does a normal insert touch? One or two is ideal. Every extra partition is an extra part per insert.
- Is the column immutable? ClickHouse cannot
UPDATEa partition key column, and a row whose partition value changes has to be deleted and re-inserted.
| Situation | Partition key | Why |
|---|---|---|
| Event or fact table kept for months or years | toYYYYMM(ts) | Drop or expire a month at a time; tens of partitions |
| Logs or traces with a TTL of days or weeks | toDate(ts) | TTL can drop whole days; few partitions because retention is short |
| Data restated a month at a time by a batch job | toYYYYMM(ts) | Rebuild the month in staging, swap it in with REPLACE PARTITION |
| Multi-tenant table | None, or toYYYYMM(ts) | Put tenant_id first in ORDER BY instead |
| Dimension, lookup or small table | None | Nothing to drop by time; one partition merges best |
| Kept forever, queried across all history | None | Partitions only add parts |
The keys to avoid are the ones whose partition count grows without bound: tenant_id, user_id or customer_id, hourly keys on long-retention tables, and tuples such as (toYYYYMM(ts), event_type) that multiply two cardinalities. The custom partitioning key reference is explicit: “Don’t partition your data by client identifiers or names. Instead, make a client identifier or name the first column in the ORDER BY expression.” Floating-point keys are refused unless you enable allow_floating_point_partition_key.
Should you partition by month or by day?
Partition by month unless retention is short and you drop data by the day. The reference page puts it this way: “In most cases you do not need a partition key, and in most other cases you do not need a partition key more granular than by month, unless targeting an observability use case where partitioning by day is common.” The TTL guide gives the matching rule from the retention side: partition by day for a TTL of days or weeks, and by month for a TTL of months or years.
The arithmetic makes the choice for you:
| Retention | Monthly partitions | Daily partitions |
|---|---|---|
| 30 days | 2 | 30 |
| 13 months | 14 | about 395 |
| 3 years | 36 | 1,095 |
| 7 years | 84 | 2,555 |
Daily partitioning on a 30-day log table is fine: 30 partitions, each one dropped whole by TTL as it expires. Daily partitioning on a seven-year fact table gives thousands of partitions, tiny parts and the slow tenant queries from the test above. Weekly keys (toMonday(ts)) sit in between and suit a TTL measured in weeks.
There is one more cost of daily keys: backfills. Loading a year of history into a daily-partitioned table means every insert block spans many partitions, which runs straight into the first limit below.
Which limits does a bad partition key hit?
Too many partitions in one insert. A single insert block may touch at most 100 partitions (max_partitions_per_insert_block, default 100). Inserting one row per day for a year into the daily table failed immediately:
Code: 252. DB::Exception: Too many partitions for single INSERT block (more than 100).
The limit is controlled by 'max_partitions_per_insert_block' setting. Large number of
partitions is a common misconception. [...] Recommended total number of partitions for
a table is under 1000..10000. Please note, that partitioning is not intended to speed up
SELECT queries (ORDER BY key is sufficient to make range queries fast). Partitions are
intended for data manipulation (DROP PARTITION, etc).. (TOO_MANY_PARTS)
The check is per block, not per statement. Our 30-million-row INSERT ... SELECT into the same daily table succeeded, because ClickHouse cut it into blocks of about a million rows (max_insert_block_size, 1,048,449 by default) and each block covered roughly 25 days. A backfill that is not sorted by time would have failed. Fix the key before you raise the setting; for a one-off backfill, insert one month at a time.
Too many parts per partition and per table. Inserts slow down when one partition has 1,000 active parts (parts_to_delay_insert) and fail at 3,000 (parts_to_throw_insert); the whole table is capped at 100,000 (max_parts_in_total). A granular key reaches these much sooner, because many partitions each receive small parts that can never merge with their neighbours. Our guide to the “Too many parts” error covers the diagnosis and fixes.
Queries that scan every partition. max_partitions_to_read (default -1, unlimited) is a guardrail you can set per query, per user profile or per table. With it set to 31, a tenant query on the daily table failed with Too many partitions to read. Current 730, max 31. (TOO_MANY_PARTITIONS), while a query filtered to the last month ran normally.
What partitions are for: dropping, replacing and moving data
This is where a partition key earns its cost. Each statement below ran against the monthly table:
-- Retention: remove a month. Metadata only; took 0.09 s here.
ALTER TABLE events DROP PARTITION 202411;
ALTER TABLE events DROP PARTITION ID '202412'; -- same, by partition_id
-- Idempotent restatement: rebuild one month in a staging table, then swap it in.
CREATE TABLE events_staging AS events;
INSERT INTO events_staging SELECT ... WHERE toYYYYMM(ts) = 202609;
ALTER TABLE events REPLACE PARTITION 202609 FROM events_staging;
-- Archive: move a month to another table (it leaves the source).
CREATE TABLE events_archive AS events;
ALTER TABLE events MOVE PARTITION 202501 TO TABLE events_archive;
-- Take a month offline and bring it back.
ALTER TABLE events DETACH PARTITION 202502;
ALTER TABLE events ATTACH PARTITION 202502;
REPLACE PARTITION is atomic and copies rather than moves: after the swap, the staging table still held its 1,232,877 rows. That makes it the cleanest way to rerun a monthly batch without duplicates or a window of missing data. According to the ALTER PARTITION reference, both REPLACE and MOVE ... TO TABLE require the two tables to have the same structure, partition key, ORDER BY, primary key and storage policy (and MOVE the same engine family, replicated or not), so create the staging table with CREATE TABLE ... AS.
Two server-side details. DROP PARTITION refuses partitions larger than max_partition_size_to_drop, 50 GB by default, as a safety check. And on an unpartitioned table the only partition is tuple(), so ALTER TABLE t DROP PARTITION tuple() empties the whole table. We did exactly that by mistake during testing.
Partitions also make TTL cheap. With the TTL expression on the same column as the partition key, expired data can go a whole part at a time instead of row by row, and the ttl_only_drop_parts = 1 table setting makes row TTL drop only parts whose rows have all expired, instead of rewriting parts to remove some of their rows:
CREATE TABLE events_ttl (tenant_id UInt32, ts DateTime, amount Decimal(12, 2))
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, ts)
TTL ts + INTERVAL 12 MONTH DELETE
SETTINGS ttl_only_drop_parts = 1;
The same pairing drives tiered storage: TTL ts + INTERVAL 3 MONTH TO VOLUME 'cold' moves whole parts to cheaper disks. For deletes that do not follow partition boundaries, see how to delete and update rows in ClickHouse.
When should you not partition a ClickHouse table?
Skip PARTITION BY when none of the operations above apply. The best-practice guide’s own advice is that if you are unsure, “start without it and optimize later based on observed access patterns.” Typical cases:
- Small and dimension tables. A few million rows of customers or products have nothing to drop by time, and one partition merges into the fewest parts.
- Tables you never delete from by time. Without a lifecycle reason, partitions only add parts and slow queries on the sort key.
- ReplacingMergeTree tables keyed on something that can cross partitions. Background merges deduplicate only inside a partition. In our test, two versions of the same
idwhosetsfell on either side of a month boundary both survivedOPTIMIZE TABLE ... FINAL; onlySELECT ... FINALcollapsed them. If a row’s partition value can change between versions, partition by something stable or not at all.
One caution on “optimize later”: the partition key cannot be changed in place. Adding or changing it means a rebuild.
How to change or audit a partition key
To change the key, create the new table, copy the data in slices and swap the names atomically:
CREATE TABLE events_v2 AS events
ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, ts);
INSERT INTO events_v2 SELECT * FROM events
WHERE ts >= '2025-01-01' AND ts < '2025-02-01'; -- repeat per month
EXCHANGE TABLES events AND events_v2;
EXCHANGE TABLES needs an Atomic (the default) or Shared database. Pause writers or replay the rows written during the copy before the swap.
To audit what you have, this query lists each table’s partition count, total parts and its smallest and largest partitions:
SELECT
database,
table,
uniqExact(partition_id) AS partitions,
sum(parts) AS parts,
formatReadableSize(min(partition_bytes)) AS smallest_partition,
formatReadableSize(max(partition_bytes)) AS largest_partition
FROM
(
SELECT database, table, partition_id,
count() AS parts, sum(bytes_on_disk) AS partition_bytes
FROM system.parts
WHERE active
GROUP BY database, table, partition_id
)
GROUP BY database, table
ORDER BY partitions DESC
LIMIT 20;
Tables with hundreds of partitions and small partition sizes are the ones to look at first. Run it on a schedule, because a key that suited last year’s volume can drift into trouble as retention grows.
If you would rather watch this continuously, Goni is one option. Full disclosure: this is our product. Its Pulse page shows a parts-pressure heatmap with each table’s part count, the part count of its worst partition, the effective parts_to_throw_insert threshold, and a projected time until inserts would be rejected. The drawback is that ClickHouse is the only warehouse Goni queries, so it does not help if yours is another; the queries in this post work on any ClickHouse deployment with no extra tooling.
FAQ
What is the best partition key in ClickHouse?
For most event and fact tables, a monthly key on the event time, toYYYYMM(ts) or toStartOfMonth(ts), so old months can be dropped or expired cheaply. For small, dimension or keep-forever tables, the best key is often none at all. Avoid keys on customer or tenant identifiers; put those first in ORDER BY instead.
Should I partition ClickHouse tables by month or by day?
By month, unless retention is short and you delete by the day. Daily keys suit logs and traces with a TTL of days or weeks, where only a few dozen partitions exist at once. On tables kept for years, daily keys create thousands of small partitions, slow queries and make backfills hit the 100-partitions-per-insert limit.
Does partitioning improve ClickHouse query performance?
Mainly in one case: a query filters on the partition column, and that column is not in the primary key (or sits deep in it), so partition pruning skips data the primary index could not. Queries on the sort-key prefix gain nothing, and queries that span many partitions read more parts. In our test, daily partitions slowed most queries.
How many partitions should a ClickHouse table have?
ClickHouse’s best-practice guide says a key with fewer than 100 to 1,000 distinct values is usually optimal, and the server’s own error message recommends staying under 1,000 to 10,000 partitions per table. Multiply your retention by the partition granularity to check before you create the table.
Can I change the partition key of an existing ClickHouse table?
No. There is no statement that changes PARTITION BY in place. Create a new table with the new key, copy the data with INSERT ... SELECT one month at a time, then swap the tables with EXCHANGE TABLES. Pause writers or replay rows inserted during the copy so none are lost.