Skip to main content
Version: 1.2.x

IF ELSE

IF ELSE statement

The IF ELSE statement can be used as a main statement, or within a parent statement, to return a value depending on whether a condition, or a series of conditions match. The statement allows for multiple ELSE IF expressions, and a final ELSE expression, with no limit to the number of ELSE IF conditional expressions.

SurrealQL Syntax
IF @condition [ THEN ]
@expression
[ ELSE IF @condition [ THEN ]
@expression ... ]
[ ELSE
@expression ]
[ END ]

Example usage

Basic usage

The following query shows example usage of this statement.

IF $scope = "admin" THEN
( SELECT * FROM account )
ELSE IF $scope = "user" THEN
( SELECT * FROM $auth.account )
ELSE
[]
END

Advanced usage

You can also have nested conditions:

IF $scope = "admin" THEN
( SELECT * FROM admin_data WHERE access_level = 'full' )
ELSE IF $scope = "user" THEN
IF $auth.role = "premium" THEN
IF $auth.subscription_status = "active" THEN
( SELECT * FROM premium_user_data WHERE active = 1 )
ELSE IF $auth.subscription_status = "trial" THEN
( SELECT * FROM trial_user_data )
ELSE
( SELECT * FROM basic_user_data )
END
ELSE IF $auth.role = "standard" THEN
( SELECT * FROM standard_user_data WHERE region = 'US' )
ELSE IF $auth.role = "standard" AND $auth.subscription_status = "active" THEN
( SELECT * FROM standard_user_data WHERE region = 'EU' )
ELSE
( SELECT * FROM unauthorized_user_data )
END
ELSE
( SELECT * FROM unknown_scope_data )
END

If-else statements can also be used as subqueries within other statements.

UPDATE person SET railcard =
IF age <= 10 THEN
'junior'
ELSE IF age <= 21 THEN
'student'
ELSE IF age >= 65 THEN
'senior'
ELSE
NULL
END
;