> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Should I use a high-precision timestamp in the primary key?

> Measures how a microsecond DateTime64 timestamp, a rounded copy of it and a rounding expression in the sorting key change the number of granules a query reads, and which one to choose.

A `DateTime64` timestamp with microsecond or nanosecond precision is fine in the primary key of a `MergeTree` table (the `ORDER BY` key, unless you define `PRIMARY KEY` separately) as long as it is the last key column. The primary index is sparse: it has one entry per granule (8192 rows by default), so it does not grow with the number of distinct values, and it finds a time range equally well at any precision.

The precision matters for the key columns that come after the timestamp. When almost every row has its own timestamp, the rows are not ordered by those columns in any useful way, and the index cannot help with filters on them. If you filter on other columns as well, put them before the timestamp, or round the timestamp in the key. The rest of this article measures the difference.

## Example data

Four tables hold the same 5 million log rows: 12 hours of data from 50 services, about 116 rows per second, every row with its own microsecond timestamp. `event_time` is a copy of the timestamp truncated to the second. The tables differ only in the sorting key.

```sql theme={null}
CREATE TABLE logs_ts
(
    ts DateTime64(6, 'UTC'),
    event_time DateTime('UTC') DEFAULT toDateTime(ts),
    service LowCardinality(String),
    duration_ms UInt32,
    message String
)
ENGINE = MergeTree
ORDER BY (ts, service);

CREATE TABLE logs_second AS logs_ts ENGINE = MergeTree ORDER BY (event_time, service, ts);
CREATE TABLE logs_hour AS logs_ts ENGINE = MergeTree ORDER BY (toStartOfHour(ts), service, ts);
CREATE TABLE logs_service AS logs_ts ENGINE = MergeTree ORDER BY (service, ts);

INSERT INTO logs_ts (ts, service, duration_ms, message)
SELECT
    toDateTime64('2026-01-01 00:00:00', 6, 'UTC')
        + toIntervalMicrosecond(number * 8640 + cityHash64(number) % 8640),
    concat('service-', toString(cityHash64(number, 1) % 50)),
    cityHash64(number, 2) % 2000,
    concat('request ', toString(cityHash64(number, 3) % 100000), ' finished')
FROM numbers(5000000);

INSERT INTO logs_second SELECT * FROM logs_ts;
INSERT INTO logs_hour SELECT * FROM logs_ts;
INSERT INTO logs_service SELECT * FROM logs_ts;

OPTIMIZE TABLE logs_ts FINAL;
OPTIMIZE TABLE logs_second FINAL;
OPTIMIZE TABLE logs_hour FINAL;
OPTIMIZE TABLE logs_service FINAL;
```

```sql theme={null}
SELECT
    count() AS rows,
    uniqExact(ts) AS distinct_ts,
    uniqExact(event_time) AS distinct_seconds,
    uniqExact(toStartOfHour(ts)) AS distinct_hours,
    uniqExact(service) AS services
FROM logs_ts;
```

```text theme={null}
   ┌────rows─┬─distinct_ts─┬─distinct_seconds─┬─distinct_hours─┬─services─┐
1. │ 5000000 │     5000000 │            43200 │             12 │       50 │
   └─────────┴─────────────┴──────────────────┴────────────────┴──────────┘
```

## Granules read by each sorting key

[`EXPLAIN ESTIMATE`](https://clickhouse.com/docs/reference/statements/explain#explain-estimate) returns the number of granules (`marks`) that a query has to read after the primary index is applied. Each of the four tables has 611 granules.

### A time range only

A filter on a five-minute window of `ts`:

```sql theme={null}
SELECT table, marks
FROM
(
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_ts
        WHERE ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 06:05:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_second
        WHERE ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 06:05:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_hour
        WHERE ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 06:05:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_service
        WHERE ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 06:05:00')
)
ORDER BY table;
```

```text theme={null}
   ┌─table────────┬─marks─┐
1. │ logs_hour    │    52 │
2. │ logs_second  │   611 │
3. │ logs_service │   101 │
4. │ logs_ts      │     5 │
   └──────────────┴───────┘
```

* `logs_ts`, with the microsecond timestamp first, reads 5 granules. High precision does no harm here.
* `logs_second` reads the whole table. Its first key column is `event_time`, the query filters on `ts`, and ClickHouse does not derive a condition on one stored column from a condition on another.
* `logs_hour` reads the 52 granules of that hour. The key contains the expression `toStartOfHour(ts)`, and ClickHouse applies a condition on `ts` to it, so queries do not have to change.
* `logs_service` reads 101 granules: about two for each of the 50 services.

For `logs_second`, the query has to filter on the key column. It then reads the same 5 granules as `logs_ts`, so rounding to the second gains nothing for this query:

```sql theme={null}
SELECT table, marks
FROM
(
    EXPLAIN ESTIMATE
    SELECT avg(duration_ms)
    FROM logs_second
    WHERE event_time >= '2026-01-01 06:00:00' AND event_time < '2026-01-01 06:05:00'
);
```

```text theme={null}
   ┌─table───────┬─marks─┐
1. │ logs_second │     5 │
   └─────────────┴───────┘
```

### A time range and another column

A filter on one service and one hour (on `event_time` for `logs_second`, on `ts` for the other tables):

```sql theme={null}
SELECT table, marks
FROM
(
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_ts
        WHERE service = 'service-7' AND ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 07:00:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_second
        WHERE service = 'service-7' AND event_time >= '2026-01-01 06:00:00' AND event_time < '2026-01-01 07:00:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_hour
        WHERE service = 'service-7' AND ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 07:00:00')
    UNION ALL
    SELECT * FROM (EXPLAIN ESTIMATE SELECT avg(duration_ms) FROM logs_service
        WHERE service = 'service-7' AND ts >= '2026-01-01 06:00:00' AND ts < '2026-01-01 07:00:00')
)
ORDER BY table;
```

```text theme={null}
   ┌─table────────┬─marks─┐
1. │ logs_hour    │     5 │
2. │ logs_second  │    52 │
3. │ logs_service │     2 │
4. │ logs_ts      │    52 │
   └──────────────┴───────┘
```

* `logs_ts` and `logs_second` read every granule of the hour. `service` comes after the timestamp in their keys and does not narrow the range. Rounding to the second does not change that: at 116 rows per second, a granule of 8192 rows spans about 70 seconds, so rows with the same `event_time` never fill a granule.
* `logs_hour` reads 5 granules and `logs_service` reads 2, because all rows of one service within an hour, or of one service overall, are stored together.

A key column helps only when the columns before it have the same values over ranges that are much longer than a granule. This is the rule given in [Selecting a primary key](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/mergetree.md#selecting-a-primary-key).

## What a rounded copy is good for

A second-precision copy of the timestamp does not improve the index, but it is cheaper to store and to process. In a table that is sorted by time, consecutive rows share the same second, and the column compresses to almost nothing:

```sql theme={null}
SELECT
    name,
    type,
    formatReadableSize(data_compressed_bytes) AS compressed,
    formatReadableSize(data_uncompressed_bytes) AS uncompressed
FROM system.columns
WHERE database = currentDatabase() AND table = 'logs_ts' AND name IN ('ts', 'event_time');
```

```text theme={null}
   ┌─name───────┬─type─────────────────┬─compressed─┬─uncompressed─┐
1. │ ts         │ DateTime64(6, 'UTC') │ 24.47 MiB  │ 38.15 MiB    │
2. │ event_time │ DateTime('UTC')      │ 264.82 KiB │ 19.07 MiB    │
   └────────────┴──────────────────────┴────────────┴──────────────┘
```

The sizes are from ClickHouse 26.12 with `LZ4` compression, and they differ between versions and codecs. Queries that work at the granularity of seconds or coarser also run faster on the smaller column. On the test machine, `SELECT toStartOfMinute(event_time) AS minute, count() FROM logs_ts GROUP BY minute` ran three to four times faster than the same query with `toStartOfMinute(ts)`.

## Recommendations

* If queries filter by time only, sort by the timestamp as it is (`ORDER BY ts`). Rounding it does not reduce the number of granules read.
* If queries filter by other columns and a time range, put those columns first, in order of increasing cardinality, and the full-precision timestamp last: `ORDER BY (service, ts)`.
* If you need both, start the key with a rounded timestamp, for example `ORDER BY (toStartOfHour(ts), service, ts)`. Choose the rounding so that one value covers many granules. With an expression in the key, queries keep filtering on `ts`.
* If dashboards filter and group by seconds, minutes or hours, add a `DateTime` column next to the `DateTime64` one, as `event_time` above, and use it in those queries. If you put the copy into the sorting key instead of an expression, queries must filter on the copy.

See also [Choosing a primary key](https://clickhouse.com/docs/concepts/best-practices/choosing-a-primary-key.md), [Ordering key columns efficiently](https://clickhouse.com/docs/guides/clickhouse/data-modelling/sparse-primary-indexes.md#ordering-key-columns-efficiently) and [Time granularity matters](https://clickhouse.com/docs/resources/support-center/tips-and-tricks/performance-optimization.md#time-granularity).
