A query that is nested inside another one is called a subquery. Subqueries are executed first, enabling their output to be used inside a larger query.
Subquery examples
SELECT inside SELECT
A SELECT can be used to populate the value of a field, which can be given an alias via the AS keyword.
To refer to part of the outer query, the preset $parent parameter can be used.
Other statements inside a larger query
Other statements such as CREATE, UPDATE and so on can be used as subqueries as well. This can be useful to combine multiple queries into one or keep statements that should either succeed or fail together inside a single transaction.
Patterns such as appending a new comment id to a record are covered in record references. See also RETURN.
$parent and $this
In nested contexts, SurrealDB predefines:
$this— the current record in the inner scope.$parent— the current record in the enclosing scope.
They let an inner SELECT relate its WHERE clause to the record being processed outside.
Full detail: Reserved variables — $parent, $this.
Graph paths and inner queries
Graph traversal (->edge->table) can include a parenthesised inner query on the edge or node, similar to filtering or projecting in a subquery. This allows you to restrict or shape the edges before the traversal continues.
Shorthand filters are often written without a nested SELECT, but the nested form is useful when you need full SELECT power (ORDER BY, GROUP BY, and so on):
More examples: Selecting inside graph queries and graph clauses on the RELATE page.