LET Statement
The LET statement allows you to create parameters to store any value, including the results of queries or the outputs of expressions. These parameters can then be referenced throughout your SurrealQL code, making your queries more dynamic and reusable.
Syntax
The syntax for the LET statement is straightforward. The parameter name is prefixed with a $ symbol.
Example Usage
Basic Parameter Assignment
You can use the LET statement to store simple values or query results. For example, storing a string value and then using it in a CREATE statement:
Storing Query Results
The LET statement is also useful for storing the results of a query, which can then be used in subsequent operations:
Conditional Logic with IF ELSE
SurrealQL allows you to define parameters based on conditional logic using IF ELSE statements:
Anonymous Functions
You can define anonymous functions also known as closures using the LET statement. These functions can be used to encapsulate reusable logic and can be called from within your queries. Learn more about anonymous functions in the Data model section.
Pre-Defined and Protected Parameters
SurrealDB comes with pre-defined parameters that are accessible in any context. However, parameters created using LET are not accessible within the scope of these pre-defined parameters.
Furthermore, some pre-defined parameters are protected and cannot be overwritten using LET:
Attempting to redefine protected parameters will result in an error:
Typed LET statements
Type safety in a LET statement can be ensured by adding a : (a colon) and the type name after the LET keyword.
Taking advantage of type safety
Using typed LET statements is a good practice when prototyping code or when getting used to SurrealQL for the first time. Take the following example that attempts to count the number of true values in a field by filtering out values that are not true, without noticing that the field actually contains strings instead of booleans. The query output ends up being 0, rather than the expected 2.
Breaking this into multiple typed LET statements shows the error right away.
With the location of the error in clear sight, a fix is that much easier to implement.
Typed literal statements
Multiple possible types can be specified in a LET statement by adding a | (vertical bar) in between each possible type.
Even complex types such as objects can be included in a typed LET statement.
For more information on this pattern, see the page on literals.
Conclusion
The LET statement in SurrealDB is versatile, allowing you to store values, results from subqueries, and even define anonymous functions. Understanding how to use LET effectively can help you write more concise, readable, and maintainable queries.