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
| Key | Type | Readonly | Description |
|---|---|---|---|
_type | SerializationType.CASE_STATEMENT | Yes | Discriminates this node during serialization. |
_expressions | { condition: SqlElement; value: any }[] | No | The when/then pairs added so far. |
_elseValue | any | No | The value set by .else(). |
_condition | LogicalOperator | undefined | No | The pending condition set by the most recent .when(), consumed by the next .then(). |
_alias | string | undefined | No | Set 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