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; avoidNullableunless 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 andGROUP BY.- Codecs chain a transform with a general compressor:
Delta,DoubleDelta(timestamps, counters),Gorilla(slowly changing floats),T64(integers) followed byLZ4(default),LZ4HCorZSTD(level). Default compression islz4. - 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:
| Column | Codec / type | Compressed | Ratio |
|---|---|---|---|
id (sequential UInt64) | default LZ4 | 11.5 MiB | 2.0 |
id_delta | Delta, ZSTD | 1.1 MiB | 20.6 |
t (timestamp +1 s per row) | default LZ4 | 11.5 MiB | 1.0 |
t_dd | DoubleDelta, ZSTD | 13.5 KiB | 870 |
url (5,000 distinct strings) | String | 13.6 MiB | 3.1 |
url_lc | LowCardinality(String) | 5.8 MiB | n/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_timeinevents_a, sorted by country first, had ratio 1.1). LowCardinalitywith more than ~100k distinct values can hurt; test.Nullabledoubles reads; prefer a default value (empty string, 0) when semantics allow.- Store timestamps as
DateTime/DateTime64, not strings; money asDecimal, notFloat. - Changing a codec on an existing column (
MODIFY COLUMN ... CODEC) applies to new parts; old parts convert on merge or mutation.
Practice questions
- Why did
DoubleDeltashrink the timestamp column 870 times but did nothing foruser_id? - When is
LowCardinality(String)a bad idea? - How would you check what a table costs per column?
References
- ClickHouse documentation, Column compression codecs; Data types
Related
ch-columnar-model · ch-sorting-key-sparse-index · ch-skipping-indexes