Understand how the ORDER BY (primary sort key) affects query performance. This is ClickHouse's most important design decision.
(region, timestamp).
The most common query is: "show me all events for customer X in the last hour."
Data is sorted by (region, timestamp). The WHERE clause filters on customer_id — which is NOT in the sort key. ClickHouse cannot skip any granules based on customer_id.
| Granule | Region | Timestamp range | Has customer 42? | Action |
|---|---|---|---|---|
| 0 | ap-south-1 | 2024-01-15 00:00 → 00:15 | Unknown | ⚠ Must read (can't skip) |
| 1 | ap-south-1 | 2024-01-15 00:15 → 00:30 | Unknown | ⚠ Must read |
| 2 | eu-west-1 | 2024-01-15 00:00 → 00:20 | Unknown | ⚠ Must read |
| 3 | eu-west-1 | 2024-01-15 00:20 → 00:40 | Unknown | ⚠ Must read |
| 4 | eu-west-1 | 2024-01-15 00:40 → 01:00 | YES | ✓ Read (matched) |
| 5 | us-east-1 | 2024-01-15 00:00 → 00:25 | Unknown | ⚠ Must read |
| ... | ... | ... | Unknown | ⚠ Must read all |
(customer_id, timestamp) — matching the most common query pattern.
Data is sorted by (customer_id, timestamp). All rows for customer 42 are physically co-located. ClickHouse reads only the granules that could contain customer 42.
| Granule | customer_id range | Timestamp range | Could have cust 42? | Action |
|---|---|---|---|---|
| 0–35 | 1 → 41 | all dates | No | ✓ Skip all |
| 36 | 42 → 42 | last week | YES | ⚠ Read → filter timestamp |
| 37 | 42 → 42 | last week | YES | ⚠ Read → filter timestamp |
| 38 | 42 → 42 | last hour | YES | ✓ Read (matched) |
| 39–1000 | 43 → ... | all dates | No | ✓ Skip all |
| ORDER BY | Query: WHERE customer_id=42 | Query: WHERE region='eu' | Both? |
|---|---|---|---|
(customer_id, timestamp) | ✓ Fast | ✗ Full scan | customer fast, region slow |
(region, timestamp) | ✗ Full scan | ✓ Fast | region fast, customer slow |
(customer_id, region, timestamp) | ✓ Fast | ✗ Full scan | customer fast, region still slow |
ORDER BY (customer_id, region) means data is sorted by customer_id first. Within the same customer, it's sorted by region. Queries filtering ONLY on region still scan everything because customers are interleaved across regions in the sort order.