Skip to main content
SQL subqueries enable reuse of the results from a selection query within another query. CockroachDB supports two kinds of subqueries:

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 WITH. For example:
This query inserts 3 rows into t, even though the surrounding query only observes 1 row using LIMIT.

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 cost-based optimizer 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 LEFT join or an INNER join. 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 computed column. 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.

Known limitations

  • Statements containing multiple modification subqueries mutating the same row could cause corruption. These statements are disallowed by default, but you can enable multiple modification subqueries with one the following: If multiple mutations inside the same statement affect different tables with FOREIGN KEY relations and ON CASCADE clauses between them, the results will be different from what is expected in PostgreSQL.

See also