Skip to main content

Case

Builds a CASE WHEN ... THEN ... ELSE ... END expression, usable anywhere an SQL element is accepted (typically as a Select column).

Constructor

Case(): Case
new Case(): Case

Dual-callable, no arguments. Build the expression with the chainable methods below.

import { Case, Gt, Select } from '@sqb/builder';

Select(Case().when(Gt('age', 16)).then(1).else(0)).from('customers');
// select case when age > 16 then 1 else 0 end from customers

Properties

KeyTypeReadonlyDescription
_typeSerializationType.CASE_STATEMENTYesDiscriminates this node during serialization.
_expressions{ condition: SqlElement; value: any }[]NoThe when/then pairs added so far.
_elseValueanyNoThe value set by .else().
_conditionLogicalOperator | undefinedNoThe pending condition set by the most recent .when(), consumed by the next .then().
_aliasstring | undefinedNoSet by .as().

Methods

when()

when(...condition: (Operator | Raw)[]): this

Sets the pending condition for the next .then() call. Multiple conditions are combined with an implicit And. Calling .when() with no arguments clears the pending condition, so a following .then() is a no-op — used to build a CASE with zero branches, which serializes to an empty string (and, e.g., Select(caseExpr) falls back to select *).

Case().when(Gt('col1', 4), Lt('col1', 8)).then(1);
// when col1 > 4 and col1 < 8 then 1

then()

then(value: any): this

Commits the pending condition (set by the preceding .when()) together with value as one WHEN ... THEN ... branch. Has no effect if there is no pending condition.

else()

else(value: any): this

Sets the ELSE value. Omit it to leave the CASE without an ELSE branch.

as()

as(alias: string): this

Sets an alias, rendered as end <alias> (no AS keyword).

Case().when(Eq('col1', 5)).then(1).as('col1');
// case when col1 = 5 then 1 end col1

See also