SurrealDB Docs Logo

Enter a search query

FOR statement

The FOR statement can be used to iterate over the values of an array, and to perform certain actions with those values.

Note

A FOR loop currently cannot access items outside its own scope, such as variables declared before the loop.

SurrealQL Syntax
FOR @item IN @iterable { @block };

Example usage

The following query shows example usage of this statement.

-- Create a person for everyone in the array FOR $name IN ['Tobie', 'Jaime'] { CREATE type::thing('person', $name) CONTENT { name: $name }; };

The following query shows the FOR statement being used update a property on every user matching certain criteria.

-- Set can_vote to true for every person over 18 years old. FOR $person IN (SELECT VALUE id FROM person WHERE age >= 18) { UPDATE $person SET can_vote = true; };

Ranges in FOR loops

Available since: v2.0.0

A FOR loop can also be made out of a range UUID of integers.

FOR $year IN 0..=2024 { CREATE historical_events SET for_year = $year, events = "To be added"; }

Limitations of FOR loops

As parameters declared outside a FOR loop cannot currently be modified inside a loop, an operation like the following is not possible.

LET $init = []; FOR $num IN 1..=3 { $init += $num; }; RETURN $init;

However, the array::fold and array::reduce functions can often be used in this case.

(<array>1..=3).reduce(|$one, $two| $one + $two);
Output
6

On this page

© SurrealDB GitHub Discord Community Cloud Features Releases Install