Skip to content

$ Cond

Conditional evaluation


Control construct: test, et, ef, etc. are q expressions.

Three expressions

If test evaluates to zero, Cond evaluates and returns ef, otherwise et.


Only the first expression test is certain to be evaluated.


Although it returns a result, Cond is a control-flow construct, not an operator.

It cannot be iterated, nor projected onto a subset of expressions.

Odd number of expressions

For brevity, nested triads can be flattened.

$[q;a;r;b;c] <=> $[q;a;$[r;b;c]]

These two expressions are equivalent:


Cond with many expressions can be translated to triads by repeatedly replacing the last three expressions with the triad.

$[q;a;r;b;s;c;d] <=> $[q;a;$[r;b;$[s;c;d]]]


$[q;a;  / if q, a
  r;b;  / else if r, b
  s;c;  / else if s, c
  d]    / else d

Cond in a signum-like function

q){$[x>0;1;x<0;-1;0]}'[0 3 -9]
0 1 -1

Even number of expressions

An even number of expressions returns either a result or the generic null.

q)$[0b;`true;0b;`foo]           / return generic null

Versions before V3.6 2018.12.06 signal cond.

Name scope

Cond’s brackets do not create lexical scope. Name scope within its brackets is the same as outside them.

Good style avoids using Cond to control side effects, such as amending variables.

Using if is a clearer signal to the reader that a side effect is intended.)

Also, setting a variable in a code branch can have unintended consequences.

Query templates

Cond is not supported inside qSQL queries. Instead, use Vector Conditional.

$ dollar, Vector Conditional
Controlling evaluation
Q for Mortals §10.1.1 Basic Conditional Evaluation