Conditionals
if branches a script on a condition. It is both a statement - run these statements only when the condition holds - and an expression that produces a value you can bind with let. Together with variables, it turns a request from a fixed pipeline into logic that reacts to data.
if is an expression
Used on the right-hand side of a let, each branch's block produces the value of the whole expression. Run the snippets on this page in order:
Chain any number of conditions with else if; the first one that holds wins:
No else means maybe none
An if expression without an else has no value to produce when the condition fails, so it produces none. That is often exactly right - "a warning, or nothing" - but if a definite value is required downstream, write the else:
Guarding writes
As a statement, if runs a block of statements - including inserts, updates, and deletes - only when the condition holds. The whole request is still one transaction, whichever branches run. Note the ; after the closing brace: a block is a statement, and the next statement needs the separator:
Branches choose the result
When the if statement is the last thing in a request, the branch that ran determines the request's result - the branches do not have to produce the same shape:
Reassigning outer variables
A branch can assign to a variable declared outside it, which is the imperative alternative to the expression form - useful when several statements in the branch contribute to the final value:
else if chain that compares the same value against many candidates reads better as a match expression - one scrutinee, one arm per case, and an else arm for the rest. See the control flow overview for how the constructs fit together.