ClickHouse offers nullable data types and functions like ifNull, nullIf, coalesce, and isNull to replace, detect, or avoid NULL values during queries.
Use ifNull(expr, alt)
to replace NULL with a fallback, nullIf(expr, target)
to return NULL when two expressions match, coalesce(v1, v2, …)
to pick the first non-NULL, and isNull(expr)
to test for NULL. All accept any compatible type, including Nullable columns.
ifNull() shines when you always want a single fallback value. Example: default missing total_amount
in Orders
to 0 during revenue aggregation to avoid NULL-propagated sums.
coalesce() scans multiple alternatives, returning the first non-NULL. It is ideal when you have cascading defaults, such as preferring Orders.total_amount
, then OrderItems.quantity*Products.price
, then 0.
Use isNull()
in WHERE filters: WHERE isNull(email)
. ClickHouse optimizes this with low-level bitmap indexes, so there is no performance penalty.
Define columns as Nullable(Type)
only when NULLs are expected. For mandatory fields like Orders.order_date
, keep them non-nullable. Supply a default value with DEFAULT
in table definition to prevent accidental NULL inserts.
Prefer explicit defaults over broad NULL usage, convert columns to Nullable only when business logic requires it, and always coalesce or ifNull before arithmetic to keep aggregates correct.
Replace NULL or empty strings in Customers.email
using coalesce(NULLIF(email,''), 'no-email@example.com')
so downstream tools receive a valid placeholder.
Functions like assumeNotNull(expr)
temporarily treat a Nullable column as non-nullable, skipping NULL checks in tight loops. Combine with arrayFilter
or sumIf
for micro-optimizations.
No. An empty string is a valid value; NULL represents absence. Use nullIf(email,'')
to convert empties into NULL when needed.
Yes. Nullable types add a compact bitmap per column, so storage overhead is minimal, but avoid them when possible to keep scans faster.
Yes. Use ALTER TABLE table MODIFY COLUMN col Nullable(Type)
. Back-fill defaults or update logic to handle new NULLs.