Overview

Compression in ClickHouse is chosen per column. The right data type and codec can change storage by orders of magnitude and speed up scans, because less data is read from disk.

Core concepts

  • Types: fixed-width integers (UInt8…UInt256), Float32/64, Decimal, Date, Date32, DateTime, DateTime64, String, FixedString(n), UUID, IPv4/6, Array, Tuple, Map, Nested, JSON, Enum. Use the smallest type that fits; avoid Nullable unless needed (it adds a separate null-mask column).
  • LowCardinality(T): dictionary-encodes a column with up to roughly tens of thousands of distinct values; smaller and faster for filters and GROUP BY.
  • Codecs chain a transform with a general compressor: Delta, DoubleDelta (timestamps, counters), Gorilla (slowly changing floats), T64 (integers) followed by LZ4 (default), LZ4HC or ZSTD(level). Default compression is lz4.
  • Choose by data shape: monotonic ids and timestamps -> Delta/DoubleDelta; text -> ZSTD; low-distinct strings -> LowCardinality.

Worked example

Three million rows, table ordered by id; each variant column holds the same values:

ColumnCodec / typeCompressedRatio
id (sequential UInt64)default LZ411.5 MiB2.0
id_deltaDelta, ZSTD1.1 MiB20.6
t (timestamp +1 s per row)default LZ411.5 MiB1.0
t_ddDoubleDelta, ZSTD13.5 KiB870
url (5,000 distinct strings)String13.6 MiB3.1
url_lcLowCardinality(String)5.8 MiBn/a

A timestamp that grows by a constant step has a constant second difference, so DoubleDelta reduces it to almost nothing. Random values (user_id in events_a) barely compress at all (ratio 1.0): no codec can fix entropy. Inspect with:

SELECT name, compression_codec, formatReadableSize(data_compressed_bytes) comp
FROM system.columns WHERE database = 'kb' AND table = 'events_c';

(I tested two ZSTD levels on the same strings; the high level was not smaller on this random-ish data, so do not assume higher levels always win: measure.)

Pitfalls and production notes

  • Codec benefits depend on sort order: a sorted timestamp column is far more compressible than the same column in random order (event_time in events_a, sorted by country first, had ratio 1.1).
  • LowCardinality with more than ~100k distinct values can hurt; test.
  • Nullable doubles reads; prefer a default value (empty string, 0) when semantics allow.
  • Store timestamps as DateTime/DateTime64, not strings; money as Decimal, not Float.
  • Changing a codec on an existing column (MODIFY COLUMN ... CODEC) applies to new parts; old parts convert on merge or mutation.

Practice questions

  1. Why did DoubleDelta shrink the timestamp column 870 times but did nothing for user_id?
  2. When is LowCardinality(String) a bad idea?
  3. How would you check what a table costs per column?

References

  • ClickHouse documentation, Column compression codecs; Data types

ch-columnar-model · ch-sorting-key-sparse-index · ch-skipping-indexes