ClickHouse ORDER BY vs PRIMARY KEY: how to choose

What the sparse primary index really does, how to pick a sort key from the queries you actually run, why column order matters, and when a projection beats a second table.

In ClickHouse, ORDER BY decides how rows are physically sorted inside each data part, and PRIMARY KEY decides which leading columns of that order go into the sparse primary index. They are the same thing unless you say otherwise: if you write only ORDER BY, ClickHouse uses it as the primary key too. If you set both, the primary key must be a prefix of the sorting key, and ClickHouse rejects the table otherwise. Neither one enforces uniqueness. The index does not point at rows. It stores one entry per granule of 8,192 rows by default and uses those entries to skip granules that cannot match a WHERE clause. That makes the sort key the most important design decision on a MergeTree table. It decides how much data each query reads and how well every column compresses, and you cannot reorder it later without rewriting the table. Below: how the index works, how to choose the key from your query log, and when to add a projection. Every query was run against ClickHouse 26.10.

ORDER BY vs PRIMARY KEY in ClickHouse: what each one does

ClauseWhat it controlsRequired?Can you change it later?
ORDER BY (sorting key)Physical row order inside each part; which rows merge together in Replacing, Summing and Aggregating MergeTreeNo in 26.10: omitting it gives an unsorted table, like ORDER BY tuple()Only by appending newly added columns
PRIMARY KEYWhich columns are stored in the in-memory sparse indexNo, defaults to ORDER BYNo, rebuild the table
PARTITION BYWhich rows share a part, for retention and data managementNoNo, rebuild the table

The MergeTree reference states the prefix rule directly, and the server enforces it:

CREATE TABLE bad (a UInt8, b UInt8)
ENGINE = MergeTree
PRIMARY KEY (b)
ORDER BY (a, b);
-- Code: 36. DB::Exception: Primary key must be a prefix of the sorting key,
-- but the column in the position 0 is a, not b. (BAD_ARGUMENTS)

If you come from Postgres or MySQL, drop the idea of a unique B-tree. Inserting the same key twice gives you two rows. Deduplication, where you need it, comes from the ReplacingMergeTree engine and only happens during merges. Our ReplacingMergeTree guide covers that in detail.

How the ClickHouse sparse primary index works

Each part stores its rows sorted by the sorting key. ClickHouse cuts those rows into granules (8,192 rows by default, or fewer if the rows are wide, because index_granularity_bytes caps a granule at 10 MiB) and writes one index entry, called a mark, holding the key values of each granule’s first row. Our 30-million-row test table has 3,663 granules, and its whole primary index takes 25 KiB of memory. That is why the index can stay in RAM for tables with billions of rows.

At query time ClickHouse compares the WHERE condition with the marks and keeps only the granule ranges that might contain matches. How well that works depends on where the filtered column sits in the key. The sparse primary index guide describes two algorithms:

  • Binary search when the query filters on the first key column (or a leading prefix). This is fast and precise.
  • Generic exclusion search when the query filters on a later column without the columns before it. This works only if the columns in front have few distinct values, so long runs of granules share the same prefix and the later column’s range inside them is narrow.

You can see which one ran, and how many granules survived, with EXPLAIN indexes = 1:

EXPLAIN indexes = 1
SELECT count()
FROM events
WHERE tenant_id = 42;
PrimaryKey
  Keys:
    tenant_id
  Condition: (tenant_id in [42, 42])
  Parts: 1/1
  Granules: 19/3663
  Search Algorithm: binary search

Granules: 19/3663 is the number to watch. The closer the first figure is to the second, the less the index is helping.

Two more details from the reference matter when you design the key. First, the index works through deterministic functions: with toDate(ts) in the key, a filter on ts is converted to a date range and still uses the index. Second, Nullable key columns are “strongly discouraged” and need allow_nullable_key, so replace NULLs with a default before the data lands.

How to choose the ORDER BY from the queries you run

Start from the workload, not the schema. If the table already exists, system.query_log tells you which query shapes read the most:

SELECT
    normalized_query_hash,
    count()                      AS runs,
    sum(read_rows)               AS rows_read,
    any(columns)                 AS columns_used,
    any(query)                   AS example
FROM system.query_log
WHERE type = 'QueryFinish'
  AND query_kind = 'Select'
  AND has(tables, 'analytics.events')
  AND event_time > now() - INTERVAL 7 DAY
GROUP BY normalized_query_hash
ORDER BY rows_read DESC
LIMIT 20
FORMAT Vertical;

columns lists every column a query touches, not only the filtered ones, so read the WHERE clause of each example. Then apply these rules in order, as ClickHouse’s own primary key best-practices page suggests:

  1. Lead with the columns that appear in most filters and exclude the most rows. In a multi-tenant table that is almost always tenant_id. In an event table it is often the event type or source.
  2. Put lower-cardinality columns before higher-cardinality ones, so the generic exclusion search still works for queries that skip the first column, and so later columns sit in long sorted runs that compress well.
  3. Add a time column at the coarsest grain your queries need. toDate(ts) or toStartOfHour(ts) instead of the raw timestamp keeps the index small and leaves room for columns after it.
  4. End with the entity id if you need fast lookups inside a prefix or deduplication with ReplacingMergeTree.
  5. Stop at four or five columns. The docs say 4-5 is typically sufficient, and the MergeTree reference warns that a long primary key hurts insert performance and memory.

For an event table queried mostly by tenant, event type and date range, that produces:

CREATE TABLE events
(
    tenant_id  UInt32,
    event_type LowCardinality(String),
    user_id    UInt64,
    ts         DateTime,
    amount     Decimal(12, 2)
)
ENGINE = MergeTree
ORDER BY (tenant_id, event_type, toDate(ts), user_id);

Test: four sort keys, same 30 million rows

To check the rules, we loaded the same 30 million synthetic events (200 tenants, 8 event types, 2 million users, about 2.8 years of timestamps) into four tables that differ only in ORDER BY, ran OPTIMIZE ... FINAL so each had one part, and counted the granules each filter selects:

ORDER BYtenant_id = 42tenant + type + one monthuser_id = 123456first day of ts
(tenant_id, event_type, toDate(ts), user_id)1913,6631,814
(toDate(ts), tenant_id, event_type, user_id)1,835533,6634
(user_id, ts)3,6633,66313,663
tuple() (no sort)3,6633,6633,6633,663

Out of 3,663 granules in total. Measured as rows read, the tenant + type + month query on the first table read 8,192 rows and returned in 3 ms. The same query read all 30 million rows in about 220 ms on the (user_id, ts) table and about 185 ms on the unsorted one. These are medians of five runs on a 2-core test container with the query cache and query condition cache turned off, so treat the milliseconds as directional. The granule and row counts are the reliable part.

Three things stand out:

  • One key serves one family of queries. The tenant-first key is excellent for tenant filters and useless for a lookup by user_id, which reads every granule. No column order fixes both.
  • The leading column’s cardinality decides how well later columns work. On the tenant-first table, a filter on the first day of the range still skipped half the granules, because only 1,600 tenant and type combinations sit in front of the date. That is the best case: a day in the middle of the range skipped only about 13%, because each of those combinations then contributes one more granule that straddles the day boundary, and the roughly 1,600 granules that straddle a tenant and type boundary can never be excluded. On the date-first table, a filter on tenant_id alone also read half the table: each of the roughly 1,040 days spans only three or four granules, so the date prefix changes too often for the exclusion search to skip much.
  • Putting time first is a valid choice for time-first workloads. It made the one-day query almost free (4 granules) and kept tenant queries over a month reasonable (53 granules). If almost every dashboard filters on a recent window and few filter by tenant alone, date first can be right. Decide with the query log, not with a rule.

Does column order affect ClickHouse compression?

Yes, and not always in the direction the rule of thumb suggests. Every column in the table is stored in sort-key order, so the columns at the front of the key form long runs of identical values that compress to almost nothing. Columns at the end look random. Here is the compressed size of each column in two of the test tables:

Column(tenant_id, event_type, toDate(ts), user_id)(user_id, ts)
tenant_id85 KiB37.7 MiB
event_type49 KiB12.5 MiB
user_id94.2 MiB4.0 MiB
ts105.8 MiB106.1 MiB
amount79.6 MiB79.6 MiB
Table total279.7 MiB239.9 MiB

The low-cardinality-first table shrank tenant_id and event_type by a factor of several hundred, but the user-first table is smaller overall. Here, user_id is an 8-byte column with 2 million distinct values, and sorting it first compressed it 24 times better, which outweighed everything else. The lesson is not to put high-cardinality ids first. Pick the key for the filters, because skipping granules is worth far more than a few percent of disk, and then check system.columns to see where your bytes actually go:

SELECT
    name,
    formatReadableSize(data_compressed_bytes)   AS compressed,
    formatReadableSize(data_uncompressed_bytes) AS raw
FROM system.columns
WHERE database = 'analytics' AND table = 'events'
ORDER BY data_compressed_bytes DESC;

When should PRIMARY KEY be shorter than ORDER BY?

Set an explicit, shorter PRIMARY KEY when the sorting key has to be long for reasons other than filtering. The classic case, given in the MergeTree reference, is SummingMergeTree and AggregatingMergeTree. Those engines collapse rows that share the whole sorting key, so every dimension must be in ORDER BY. Queries usually filter only on the first two:

CREATE TABLE daily_revenue
(
    tenant_id UInt32,
    day       Date,
    country   LowCardinality(String),
    plan      LowCardinality(String),
    channel   LowCardinality(String),
    revenue   Decimal(18, 2)
)
ENGINE = SummingMergeTree
PRIMARY KEY (tenant_id, day)
ORDER BY (tenant_id, day, country, plan, channel);

The index holds only (tenant_id, day), so it stays small, while rows are still sorted and summed by all five columns. ReplacingMergeTree tables with a long deduplication key benefit in the same way. For a plain MergeTree table with a key of four columns or fewer, leave PRIMARY KEY out.

Can you change the ORDER BY of an existing ClickHouse table?

Only a little. ALTER TABLE ... MODIFY ORDER BY changes metadata only, so it can only append columns that you add in the same statement. Existing parts are already sorted by the new key, because the new column has no values yet:

-- Works: the new column is added in the same ALTER
ALTER TABLE events
    ADD COLUMN session_id UInt64,
    MODIFY ORDER BY (tenant_id, event_type, toDate(ts), user_id, session_id);

-- Fails: amount already exists
ALTER TABLE events
    MODIFY ORDER BY (tenant_id, event_type, toDate(ts), user_id, amount);
-- Code: 36. DB::Exception: Existing column amount is used in the expression
-- that was added to the sorting key. You can add expressions that use only
-- the newly added columns. (BAD_ARGUMENTS)

You cannot reorder, remove, or change the direction of existing key columns, and the primary key stays as it was. To change the key for real, build a new table and swap it in. On the default Atomic database engine, EXCHANGE TABLES swaps the two names atomically:

CREATE TABLE events_new AS events
ENGINE = MergeTree
ORDER BY (tenant_id, event_type, toDate(ts), user_id);

INSERT INTO events_new SELECT * FROM events;   -- batch by partition on large tables

EXCHANGE TABLES events AND events_new;
DROP TABLE events_new;                          -- now holds the old data

Stop writes or capture them during the copy, and recreate any materialized views that point at the table. Our Postgres to ClickHouse migration playbook shows a batched backfill pattern that also works here.

When to add a projection instead of changing the sort key

When the query log shows two important access patterns that need different leading columns, such as tenant dashboards and support lookups by user_id, no single key serves both. The sparse index guide lists three options: a second table you write to yourself, a materialized view, or a projection. A projection is the most transparent: you keep querying the original table, and ClickHouse picks the projection when it reads less.

ALTER TABLE events
    ADD PROJECTION by_user (SELECT * ORDER BY user_id);

ALTER TABLE events MATERIALIZE PROJECTION by_user;  -- backfills existing parts

On the test table, the user_id = 123456 lookup went from reading all 30 million rows to 8,192, in about 2 ms, with system.query_log.projections confirming the projection was used. The cost was a second sorted copy of the data: 237 MiB on top of a 280 MiB table, plus the extra write on every insert.

Since 25.5, a projection can store only its sort key and the _part_offset virtual column, which makes it behave like an index into the base table, according to the projections guide:

ALTER TABLE events
    ADD PROJECTION by_user_index (SELECT _part_offset ORDER BY user_id);

On our data it took 107 MiB instead of 237 MiB, and the same lookup read 155,648 rows in about 6 ms. It is slower than the full copy because it fetches the matching rows from the base table, which are spread across the tenant-sorted data, but it is still far better than a full scan. Rules of thumb:

  • Another sort order on the same rows: projection (full copy if the query reads many columns, _part_offset if it fetches a few rows).
  • Pre-aggregated rollups or data from several tables: a materialized view. Our materialized views vs projections comparison covers that trade-off.
  • A filter that is selective but never leads a query: a data-skipping index can be cheaper, but test it, because skipping indexes help only when matching values cluster in a few granules.

Check the limits before adding projections to a table you also mutate. The projections guide lists restrictions on lightweight updates and deletes, and a projection cannot have its own TTL.

Common ORDER BY mistakes

  • Copying the OLTP primary key. ORDER BY id on a fact table makes every analytical filter a full scan.
  • Leading with a raw timestamp. A DateTime or DateTime64 first makes every later key column almost useless to the index. Use a coarser function, or put time after the main filter columns.
  • Too many columns. Each extra column costs memory and insert time, and columns after a high-cardinality one rarely help filtering.
  • Mutable columns in a ReplacingMergeTree key. The sort key defines identity, so a row whose status changes becomes a second row that never merges with the first.
  • Never checking EXPLAIN indexes = 1. Most bad keys are obvious once you see Granules: 3663/3663 on a dashboard query.

Keeping sort keys honest over time

A good key reflects the workload when you designed it, and workloads drift. Re-run the query log analysis every quarter, look for top queries that select most of their table’s granules, and decide between a projection and a rebuild. Watch part counts too, because a rebuild with a too-granular PARTITION BY can trigger the too many parts error.

If ClickHouse is your warehouse, Goni is one way to keep this loop in a single place. Its Query log browses system.query_log with per-tenant attribution, and the Doctor agent diagnoses a slow query from EXPLAIN output, scan estimates and system.parts, then suggests a rewrite. Semantic-layer models let you set the sort key per model with config(order_by=...). The trade-off is that ClickHouse is the only warehouse Goni queries, so these tools do not help on Snowflake or BigQuery. You can try it with the 14-day free trial.

FAQ

What is the difference between ORDER BY and PRIMARY KEY in ClickHouse?

ORDER BY sets how rows are sorted on disk inside each part. PRIMARY KEY sets which leading columns of that order go into the sparse index. By default they are identical. If you specify both, the primary key must be a prefix of ORDER BY. Neither enforces uniqueness, so duplicate keys are allowed.

Is the ClickHouse primary key unique?

No. ClickHouse accepts any number of rows with the same primary key. The key only controls sorting and which granules a query can skip. If you need one row per key, use ReplacingMergeTree, which removes duplicates during background merges, and deduplicate at read time with FINAL or argMax until those merges have run.

How many columns should a ClickHouse ORDER BY have?

Usually two to five. ClickHouse’s best-practices guide says four or five are typically enough. Each extra column adds index memory and insert cost, and columns after a high-cardinality column rarely help filtering. Use an explicit shorter PRIMARY KEY if an engine such as SummingMergeTree needs a longer sorting key.

Should the lowest-cardinality column come first in ORDER BY?

Generally yes, among the columns your queries filter on. Low-cardinality leading columns let ClickHouse skip granules even when a query filters only on a later column, and they compress well. But filter frequency comes first: a column that appears in almost every WHERE clause belongs at the front even if its cardinality is higher.

Can I change the ORDER BY of a ClickHouse table?

Only by appending columns added in the same ALTER TABLE ... MODIFY ORDER BY statement. You cannot reorder, remove or reverse existing key columns. To change the key, create a new table with the new ORDER BY, copy the data with INSERT ... SELECT, and swap the names with EXCHANGE TABLES. Or add a projection for the second access pattern.