Skip to main content
SQL subqueries enable reuse of the results from a within another query. CockroachDB supports two kinds of subqueries:
  • Relational subqueries, which appear as operands in and .
  • Scalar subqueries, which appear as operands in a .

Data writes in subqueries

When a subquery contains a data-modifying statement (INSERT,DELETE, etc.), the data modification is always executed to completion even if the surrounding query only uses a subset of the result rows. This is true for subqueries defined using the notation and those defined using . For example:
This query inserts 3 rows into t, even though the surrounding query only observes 1 row using .

Correlated subqueries

A subquery is said to be correlated when it uses table or column names defined in the surrounding query. For example, to find every customer with at least one order, run:
The subquery is correlated because it uses c defined in the surrounding query. The supports most correlated subqueries, with the exception of correlated subqueries that generate side effects inside a CASE statement.

LATERAL subqueries

A LATERAL subquery is a correlated subquery that references another query or subquery in its SELECT statement, usually in the context of a or an . Unlike other correlated subqueries, LATERAL subqueries iterate through each row in the referenced query for each row in the inner subquery, like a for loop. To create a LATERAL subquery, use the LATERAL keyword directly before the inner subquery’s SELECT statement. For example, the following statement performs an INNER join of the users table and a subquery of the rides table that filters on values in the users table:
LATERAL subquery joins are especially useful when the join table includes a . For example, the following query joins a subquery of the rides table with a computed column (adjusted_revenue), and a subquery of the vehicles table that references columns in the rides subquery:
In a LATERAL subquery join, the rows returned by the inner subquery are added to the result of the join with the outer query. Without the LATERAL keyword, each subquery is evaluated independently and cannot refer to objects defined in separate queries.

Performance best practices

The results of scalar subqueries are loaded entirely into memory when the execution of the surrounding query starts. To prevent execution errors due to memory exhaustion, ensure that subqueries return as few results as possible.

See also