How does ClickHouse's sparse primary index skip granules, and when does it skip almost none?
The index keeps one mark per granule (8192 rows by default). A filter on a key prefix binary-searches the marks and skips granules; one on a later column behind high-cardinality ones excludes almost none. Put filtered, low-cardinality columns first.
- Treating the sparse index as a B-tree with one entry per row
- Expecting a filter on any ORDER BY column to skip granules as well as a prefix filter does
- Putting a high-cardinality column such as user_id first when queries filter by other columns
- How does
EXPLAIN indexes = 1show how many granules a query kept? - When does a data-skipping index or a projection help a filter that misses the key prefix?
The sparse index does not point at rows. For each granule (up to 8192 rows by default, index_granularity) it stores the key values of the granule's first row — a mark. All marks fit in memory.
CREATE TABLE events
(
user_id UInt64,
event_type LowCardinality(String),
event_time DateTime
)
ENGINE = MergeTree
ORDER BY (user_id, event_type, event_time);
-- Key prefix: binary search over the marks, only the user_id = 42 granules are read
SELECT count() FROM events WHERE user_id = 42;
-- Third column behind the high-cardinality user_id: user_id changes inside almost
-- every granule, so the event_time range excludes almost nothing
SELECT count() FROM events WHERE event_time >= now() - INTERVAL 1 HOUR;For a filter that misses the prefix, ClickHouse falls back to a generic exclusion search: a granule can be dropped only where the preceding key columns stay constant across it. The lower the cardinality of the leading columns, the longer those runs and the more granules are excluded. Hence the rule: put the columns queries filter on most first, and among them the lower-cardinality ones. Check with EXPLAIN indexes = 1: the Granules: N/M line under PrimaryKey shows how many granules were kept.