ClickHouse Functions/Conditional Functions

if

Inline conditional — the ternary operator of ClickHouse SQL.

Signature

if(condition: UInt8, then: T, else: T): T

Returns

Same type as then/else branches

What it does

Returns the "then" value when condition is non-zero (true), otherwise returns the "else" value. Equivalent to CASE WHEN cond THEN then ELSE else END but more concise.

if() is the idiomatic ClickHouse ternary. It evaluates both branches but only returns the matching one — important for performance when branches involve heavy computation. For multi-way branching use multiIf(). For NULL-safe replacement use ifNull() or coalesce(). Combined with sumIf, avgIf, countIf, it avoids the need for CASE WHEN in most analytics patterns.

Notes

  • Both branches are evaluated — use multiIf() for short-circuit behaviour in expensive branches.
  • ifNull(col, default) is a specialised shorthand for if(col IS NULL, default, col).
  • In SELECT, if() can be used to build pivot-like outputs without subqueries.

Example SQL

if in ClickHouse SQL

if-example.sql

TypeScript with hypequery

Use if in a typed TypeScript query

hypequery gives you a type-safe query builder for ClickHouse. The generated schema maps your ClickHouse columns to TypeScript types, and raw SQL expressions let you incorporate functions like if when you need them inside a builder query.

user-classification.ts

Common questions

What developers search for with if

ClickHouse CASE WHEN alternative

if(cond, a, b) is shorter than CASE WHEN cond THEN a ELSE b END. For multiple branches, use multiIf(cond1, val1, cond2, val2, ..., default).

FAQ

Frequently asked questions about if

Does ClickHouse if() short-circuit evaluate?

No. Both branches are evaluated. For short-circuit behaviour (important when one branch throws on NULL), wrap in multiIf with a NULL guard.

Related functions

Functions used alongside if

Next step

Use if in a type-safe TypeScript query

hypequery generates TypeScript types from your ClickHouse schema. Use if alongside the builder, and reach for raw SQL expressions when the function is not exposed as a dedicated helper.