gsql/ Control Flow
Last Updated: October 20, 2018Implementing conditional and iterative logic in GSQL queries.
Control Flow
GSQL provides standard control flow statements that can be used at the Query Body level (top-level logic) or the DML-Sub level (inside clauses like ACCUM).
1. Conditional Logic
IF...ELSE
Standard branching logic. Use THEN and END to wrap blocks.
gsqlterminalIF @@num_friends > 10 THEN PRINT "Popular User"; ELSE IF @@num_friends > 0 THEN PRINT "Active User"; ELSE PRINT "Quiet User"; END;
CASE Statement
Supports both "Switch-style" and "Conditional-style" logic.
gsqlterminal# Switch-style CASE v.gender WHEN "Male" THEN @@males += 1 WHEN "Female" THEN @@females += 1 ELSE @@unknown += 1 END; # Conditional-style CASE WHEN v.age < 18 THEN @@minors += 1 WHEN v.age >= 18 THEN @@adults += 1 END;
2. Iterative Logic
WHILE Loop
Iterates until a condition is false. Use an optional LIMIT to prevent infinite loops.
gsqlterminalWHILE visited_vertices.size() > 0 LIMIT 10 DO visited_vertices = SELECT t FROM visited_vertices:s -(:e)-> :t WHERE t.@visited == false POST-ACCUM t.@visited = true; END;
FOREACH Loop
Iterates over a range or a collection (List, Set, Bag).
gsqlterminal# Range-based FOREACH i IN RANGE[0, 5] DO @@sum += i; END; # Collection-based FOREACH item IN @@my_list DO PRINT item; END;
3. Loop Control
BREAK: Exits the current loop immediately.CONTINUE: Skips the rest of the current iteration and starts the next one.
[!IMPORTANT] Query-Body vs. DML-Sub: Statements at the query-body level end with a semicolon (
;). Statements inside a DML clause (likeACCUM) are comma-separated.