ClickHouse Nullable performance: 9 bytes per UInt64 row, even when 99% are NULL

A ClickHouse Nullable(UInt64) column costs 9 bytes per row before compression at any NULL share. Since 25.12 a mostly-NULL column can go sparse: 0.09 B.

Every ClickHouse guide says the same thing about Nullable: avoid it, it is slow. Few say what it costs, or when. The cost has a simple shape. A Nullable(T) column is two columns on disk: a null map of 1 byte per row and the full T column, with a default value (0, empty string) written into every NULL slot. A Nullable(UInt64) therefore carries 9 bytes per row before compression, whether 1% or 99% of the rows are NULL.

The second half of that sentence is the interesting part, because it changed. Since 25.12 a MergeTree setting, nullable_serialization_version = 'allow_sparse', lets a mostly-NULL column use sparse serialization. It is off by default in 26.10. With it, a part where 99% of a Nullable(UInt64) is NULL stores about 0.09 bytes per row, and aggregates skip the NULLs without touching them.

This is day 10 of the ClickHouse series. Everything below comes from the source at tag v26.10.2.103-stable, the ClickHouse docs and published measurements by others. The byte tables are arithmetic on the serialization code, not benchmarks.

The short answer

Column type Bytes per row before compression Extra vs plain
UInt8 → Nullable(UInt8) 1 → 2 +100%
UInt32 / DateTime → Nullable(...) 4 → 5 +25%
UInt64 / Float64 → Nullable(...) 8 → 9 +12.5%
String (~20-byte values) → Nullable(String) ~21 → ~22 ~+5%
LowCardinality(String) → LowCardinality(Nullable(String)) same 0 (NULL is dictionary entry 0, no null map)
Nullable(UInt64), 99% NULL, allow_sparse 9 → ~0.09 −99%

What Nullable really costs, in order of how often it bites:

  1. One extra stream per column. A second .bin file and a second set of marks per column and part, and every read of the column reads both.
  2. No Nullable in the sorting key unless you set allow_nullable_key, which is off by default.
  3. Bigger aggregate states. sum(Nullable(UInt64)) keeps 16 bytes per group instead of 8.
  4. The NULL slots are not free. A mostly-NULL column still stores and decompresses a full column of zeros, unless it goes sparse.

What it does not cost: the per-row branch people imagine. sum over a Nullable integer runs branch-free, multiplying each value by a 0/1 mask (see below).

What a Nullable column puts on disk

Nullable(T) is a wrapper. SerializationNullable.cpp enumerates two substreams: NullMap, written as UInt8 per row, and NullableElements, the nested T column. In a Wide part they become two files, x.null.bin and x.bin, each with its own marks. The Nullable docs describe the same thing: “ClickHouse uses a separate file with NULL masks in addition to normal file with values”, and the best-practices page adds that it “almost always negatively affects performance”. Neither page puts a number on it.

The nested column has one entry per row, NULL or not. A NULL slot holds the type’s default: ColumnNullable inserts a default into the nested column for every NULL. So the values file is exactly as long as a plain column’s.

Eight rows of Nullable(UInt64), two of them not NULL: what goes to diskNULL42NULLNULLNULLNULL7NULLUInt64 DEFAULT 0x.bin: 8 B/row04200007064 BNullable, basicx.null.bin: 1 B/row101111018 Bx.bin: 8 B/row, 0 in NULL slots04200007064 BNullable, allow_sparseoffsets: gap before each value144272 gaps (1 B) + 2 values (8 B)+ one 9-byte end-of-granule varint per granule (here the whole 8 rows)27 BUncompressed bytes. Basic Nullable always costs 9 B/row for UInt64, however many rows are NULL.
Streams per SerializationNullable.cpp and SerializationSparse.cpp at v26.10.2.103. Sizes before compression.

Two side effects follow from the null map being a UInt8 column:

  • It is cheap to read alone. With optimize_functions_to_subcolumns (on by default, Settings.cpp), isNull(x), isNotNull(x) and count(x) read only the x.null subcolumn: 1 byte per row instead of 9.
  • It sits behind the same 64 KiB block floor as any narrow column (day 9). A compressed block closes only after 64 KiB, so one null-map block covers 65,536 rows. A point lookup on a Nullable column decompresses 65,536 null-map bytes on top of the value block.

Where it hurts: mostly-NULL columns

The common case for Nullable is a column that is usually empty: an optional error_code, a deleted_at, a discount that applies to 1% of orders. In the basic layout the cost of that column does not depend on how empty it is:

Share of NULLs Basic: bytes/row allow_sparse: bytes/row Ratio
0% 9 9 (stays basic) 1×
50% 9 9 (stays basic) 1×
90% 9 9 (stays basic) 1×
95% 9 0.45 20×
99% 9 0.094 96×
99.9% 9 0.011 820×

Nullable(UInt64), before compression, NULLs at random positions. The sparse column: for each non-NULL row the 8-byte value plus a variable-length gap count (1 byte for gaps under 128, 2 bytes under 16,384), plus one 9-byte end-of-granule marker per 8,192 rows. The expected gap length is 1 + p^128 + p^16384 bytes for NULL share p.

Compression changes the absolute numbers. A run of zero bytes compresses to almost nothing with LZ4 or ZSTD, so the basic layout is much smaller on disk than 9 B/row. What compression does not remove is the work: at query time the reader still decompresses and scans 9 bytes for every row, 99% of them zero.

Nullable(UInt64): bytes per row before compression, by share of NULLs0% NULLbasic: 9 B/row9 Ballow_sparse: 9 B/row9 B (stays basic)50% NULLbasic: 9 B/row9 Ballow_sparse: 9 B/row9 B (stays basic)90% NULLbasic: 9 B/row9 Ballow_sparse: 9 B/row9 B (stays basic)95% NULLbasic: 9 B/row9 Ballow_sparse: 0.451 B/row0.451 B99% NULLbasic: 9 B/row9 Ballow_sparse: 0.094 B/row0.094 B99.9% NULLbasic: 9 B/row9 Ballow_sparse: 0.011 B/row0.011 Bbasic (default)nullable_serialization_version = 'allow_sparse'log scale · sparse only above 93.75% NULL · arithmetic, random NULL positions, not a measurement
Before compression. Sparse cost = non-NULL share × (8-byte value + varint gap) + one end-of-granule varint per 8,192 rows. On disk the basic zeros compress well, so the gap there is smaller; what doesn't shrink is the work to decompress and scan them.

How allow_sparse works

Sparse serialization has existed for plain columns for years: a column where more than ratio_of_defaults_for_sparse_serialization (default 0.9375) of the values are defaults is written as offsets plus non-default values (MergeTree settings). For Nullable columns the “default” is NULL, and until 25.12 Nullable was simply excluded.

In 26.10 the switch looks like this (SerializationInfoSettings.cpp):

if (type.isNullable())
{
    if (nullable_serialization_version == MergeTreeNullableSerializationVersion::BASIC)
        return false;
    /// Skip support for sparse serialization of Nullable(Tuple) for now
    ...
}

The setting is declared in MergeTreeSettings.cpp with two values, basic (default) and allow_sparse, and the history entry “25.12, New setting”. What changes once a part goes sparse:

  • No null map is written. SerializationSparse.cpp swaps the nested serialization for one with use_default_null_map: every stored value is non-NULL by definition. The x.null subcolumn is rebuilt from the offsets when you ask for it.
  • Offsets are gaps. Each non-NULL value is preceded by a VarUInt count of the NULLs before it. A granule ends with a gap count tagged with bit 62 (END_OF_GRANULE_FLAG), which makes that one varint 9 bytes long.
  • Aggregates skip NULLs without reading them. The Nullable aggregate wrapper’s addManyDefaults is an empty function, and addBatchSparseSinglePlace hands only the stored values to the nested function (AggregateFunctionNull.h). A sum over a 99%-NULL column touches 1% of the rows.
  • The choice is per part and per column. The writer counts defaults while writing a part and picks sparse only if the ratio is above 0.9375 (chooseKindStack in SerializationInfo.cpp). Merges decide again. system.parts_columns.serialization_kind shows what each part got.

Turning it on:

CREATE TABLE orders
(
    order_id   UInt64,
    created_at DateTime,
    discount   Nullable(Decimal(10, 2))   -- set on ~1% of orders
)
ENGINE = MergeTree
ORDER BY (created_at, order_id)
SETTINGS nullable_serialization_version = 'allow_sparse';
-- existing table: ALTER TABLE orders MODIFY SETTING nullable_serialization_version = 'allow_sparse';
-- new parts use it; old parts change when they are merged

SELECT name, column, serialization_kind
FROM system.parts_columns
WHERE table = 'orders' AND active AND column = 'discount';

Two cautions. The setting is new and opt-in, and it has had a run of correctness fixes since it landed in #88999 (25.12): sparse/Nullable substreams in Tuples that “could lead to corrupted parts” (#91932), and shifted string offsets of sparse Nullable(String) over the native protocol, fixed in 26.10 and backported to 26.8 (#126937). Run a recent patch release and test it on a copy of your table first. And parts written with it record the nullable serialization version in serialization.json; a server older than 25.12 can’t read them, so finish a cluster upgrade before you enable it (the same reason serialization_info_version exists, per its description).

Aggregates: no branch, but a bigger state

Any aggregate over a Nullable argument is wrapped in AggregateFunctionNull. Two things in that wrapper matter.

The hot loop is branch-free. For sum, the wrapper passes the null map down to addBatchSinglePlaceNotNull, and AggregateFunctionSum.h turns the NULL check into arithmetic. For integers and decimals it multiplies each value by 0 or 1; for Float32/Float64 it ANDs the bits with an all-zeros or all-ones mask, unrolled. Both vectorise. The comment in the source links a quick-bench comparison. The price is reading the extra byte per row, not mispredicting a branch per row.

The state grows by one alignment unit. When the result can be NULL (it can for sum, min, max, avg; not for count or uniq, which return a default), the wrapper stores a “has a value” flag in front of the nested state. To keep the nested state aligned, the flag takes alignOfData() bytes, not one:

prefix_size(result_is_nullable ? nested_function->alignOfData() : 0)

A sum(Nullable(UInt64)) state is 8 bytes of flag plus 8 bytes of sum: 16 bytes per group instead of 8. In a GROUP BY with 100 million keys and four such sums, that is 3.2 GB more hash-table state before any key overhead. The serialized state also gains a byte (serialize_flag), which you pay in AggregatingMergeTree and in distributed merges.

What others measured

No neutral benchmark of allow_sparse exists yet that I could find. For the basic layout there are a few published numbers, and the most useful ones come from ClickHouse’s own pull requests:

Source Version Setup Nullable Plain
rushter.com not stated (June 2026) 1B rows, Nullable(UInt32) ~50% NULL, GROUP BY path, user_id 13.70 s, 553 MiB 10.15 s, 397 MiB
same size on disk 2.24 GiB (.null.bin 187 MB) 2.06 GiB
PR #125011 before 26.10 ClickBench Q30, 90 sums of ResolutionWidth + k 0.264 s 0.018 s
same 26.10 same query after the fix 0.025 s 0.018 s
PR #124868 before 26.10 → 26.10 100M rows, GROUP BY two Nullable number keys 1,796 → 865 ms, 10.29 → 4.53 GiB n/a
Google Group 2019 10M rows, GROUP BY 0.101 s 0.043 s

Three things stand out.

  • The null map is small on disk; the processing isn’t. rushter’s 187 MB for 1 billion rows is 0.19 bytes per row at ~50% NULL. If those NULLs are random, information theory puts the floor at 1 bit (0.125 bytes) per row, so the codec gets within 1.5× of it. The whole table grew 9% on disk, while the query took 35% longer and 39% more memory.
  • Much of the old “Nullable is 2-15× slower” was missed optimisations, not the format. PR #125011 (26.10) made Nullable columns get the same query optimisations as plain ones; before it, Q30 was 15× slower on the Nullable table, after it 1.4×. A chDB issue on 26.9 (chdb-core #262) hit the same gap through Parquet schema inference: 0.293 s with Nullable, 0.029 s without. If you read Nullable benchmarks, check the version.
  • A null map without NULLs is almost free on disk. The still-open PR #125020, which proposes not writing it at all (a compact_null_map value for the same setting), quotes 4,482 bytes per million rows for an all-zero null map today. The cost there is reading and processing it: on one 738k-row, 105-column query its uncompressed bytes were 633 MB with null maps and 556 MB without.

Keys, JOINs and the NULL you didn’t ask for

  • Sorting key. ORDER BY and PRIMARY KEY reject Nullable columns unless the table has allow_nullable_key = 1 (default false, MergeTreeSettings.cpp). A column you filter by most often belongs in the key, so making it Nullable usually costs you the primary index, which is far more than 1 byte per row.
  • JOINs don’t create Nullable unless asked. With the default join_use_nulls = 0, rows without a match get the type’s default value, not NULL. Turn it on and the result columns become Nullable, with the costs above on every downstream step.
  • Inserting NULL into a non-Nullable column works. input_format_null_as_default is on by default, so a NULL in CSV, JSON or INSERT ... VALUES becomes the column’s default. You don’t need Nullable just because the source sends nulls.

When Nullable is worth it

Use Nullable when “unknown” and “zero” mean different things and both appear: a temperature where 0 °C is real, a score where 0 is a valid result, a SQL-standard avg that must skip missing values. A sentinel like -1 or 1970-01-01 is cheaper, but every query then has to remember it.

A decision table:

Situation Choice
Missing and 0 mean the same Plain column with DEFAULT
Missing ≠ 0, column filtered or sorted on Plain column + sentinel, or a separate has_x flag; keep it in the key
Missing ≠ 0, mostly present Nullable: +1 B/row, small after compression
Missing ≠ 0, mostly (>94%) missing Nullable + nullable_serialization_version = 'allow_sparse' (25.12+)
Low-cardinality strings LowCardinality(Nullable(String)): NULL is a dictionary entry, no null map

The LowCardinality row comes from ColumnUnique.h: a nullable dictionary reserves index 0 for NULL and index 1 for the default value (numSpecialValues = 2), and SerializationLowCardinality.cpp writes only dictionary keys and indexes, no null-map stream. Day 5 of this series covered LowCardinality itself.

FAQ

Does Nullable make ClickHouse queries slower? It adds a 1-byte-per-row null map that every read of the column decompresses, larger aggregate states (16 instead of 8 bytes for sum over UInt64), and it keeps the column out of the sorting key unless allow_nullable_key is set. Aggregation loops stay vectorised. The biggest cost in practice is a column that is mostly NULL, which still stores a full column of defaults.

How much disk does Nullable use? Before compression, 1 extra byte per row. After compression it depends on the data: a null map that is all zeros, or long runs, compresses to very little. Check your own table with system.columns (data_compressed_bytes) or system.parts_columns, which list the column’s streams together.

What is nullable_serialization_version? A MergeTree setting added in 25.12. basic (default) keeps the null map layout; allow_sparse lets parts where more than 93.75% of a Nullable column is NULL store only the non-NULL values and their positions.

Does count(x) read the whole Nullable column? No. With optimize_functions_to_subcolumns = 1 (default) count(x), isNull(x) and isNotNull(x) read only the x.null subcolumn.

Can I use a Nullable column in ORDER BY? Only with the table setting allow_nullable_key = 1. It is off by default; most schemas are better off with a non-Nullable key column and a default value.

Tomorrow, day 11: ReplacingMergeTree, and what FINAL, argMax and LIMIT BY cost as the table grows.