The RETURN statement can be used to return an implicit value or the result of a query, and to set the return value for a transaction, block, or function.
Statement syntax
SurrealQL Syntax
RETURN@value
Example usage
Basic usage
RETURN is always followed by a value. As every data type in SurrealDB is a type of value, the RETURN statement can return anything from simple values to the result of queries.
-- Return a simple value RETURN123; RETURN"I am a string!"; RETURN{ prop: "value" };
-- Return the result of a query RETURNSELECT * FROMperson; RETURN (CREATEperson).id;
Values on their own are treated as if they have an implicit RETURN in front. As such, the following queries return the same output as in the previous example.
123; "I am a string!"; { prop: "value" }; SELECT * FROMperson; (CREATEperson).id;
Transaction return value
RETURN statements can set the result of any transaction. This includes transactions, blocks and functions.
Transaction return value
BEGINTRANSACTION;
-- We are executing quite a few queries here LET$firstname = "John"; LET$lastname = "Doe";
-- But because we end with a RETURN query, only the person's ID will be returned -- The results of the other queries will be omitted. RETURN$person.id;
-- One issue with this approach is that query errors are generic. -- To get around that, use a block, which is executed as a transaction by itself.
COMMITTRANSACTION;
Return breaks execution
Unlike RETURN in SurrealDB 1.x, RETURN now breaks execution of statements, functions and transactions.
DEFINEFUNCTIONfn::round::up($num: number) { IF$num % 2 ==0{ RETURN$num; -- Breaks execution for the function };
-- This is only executed if the RETURN inside the IF statement did not break execution RETURN$num+1; };
Transactions
BEGIN; RETURN1; -- Is executed CREATEa; -- Is not executed RETURN2; -- Is not executed COMMIT;
Lastly, if not executed inside a transaction or function, RETURN will break execution until the most top-level statement it is executed in. RETURN will not prevent top level statements from being executed, nor will it adjust their output.