Subquery
A subquery is a SQL query nested inside another query (typically a SELECT statement). It can appear in the SELECT, FROM, WHERE, or HAVING clause to provide data or conditions for the outer query. With subqueries, you can implement more complex filtering, aggregation, and join logic in a single SQL statement.
This document describes the categories of subqueries in VeloDB Cloud, the supported scope, the limitations, and the Mark Join mechanism used in special scenarios.
Applicable scenarios
Subqueries are commonly used in the following scenarios:
- Complex filtering: Use a subquery in the
WHEREorHAVINGclause to dynamically compute filter conditions. - Derived column computation: Use a scalar subquery in the
SELECTlist to add an extra field. - Derived table: Use a subquery in the
FROMclause as a temporary table that participates in a join. - Existence checks: Use
EXISTS/NOT EXISTSorIN/NOT INto evaluate relationships between sets.
Basic characteristics of subqueries
When using subqueries, keep the following basic characteristics in mind:
| Characteristic | Description |
|---|---|
| Position | Can appear in the SELECT, FROM, WHERE, or HAVING clause, and can be combined with SELECT, UPDATE, INSERT, DELETE, as well as expression operators such as =, >, <, <=, IN, and EXISTS. |
| Outer/Inner relationship | The outer query is called the main query, and the query nested inside it is called the subquery. |
| Execution order | The optimizer determines the execution plan and can rewrite subqueries as joins. SQL nesting does not prescribe physical execution order. |
| Syntax constraint | A subquery must be wrapped in parentheses to distinguish it from the main query. |
Create the example tables in a database where you can create tables. The queries below demonstrate syntax and restrictions. Their results depend on the rows you insert.
create table t1
(
c1 bigint,
c2 bigint
)
DISTRIBUTED BY HASH(c1) BUCKETS 3;
create table t2
(
c1 bigint,
c2 bigint
)
DISTRIBUTED BY HASH(c1) BUCKETS 3;
Categories of subqueries
Subqueries can be classified along two dimensions: the characteristics of the returned data and whether they reference columns from the outer query.
Classification by returned data characteristics
By the characteristics of the data returned, subqueries can be divided into scalar subqueries and non-scalar subqueries.
| Type | Returned result | Return value when the table is empty | Allowed positions |
|---|---|---|---|
| Scalar subquery | A single value (a relation with one row and one column) | NULL | Anywhere a single-value expression is allowed |
| Non-scalar subquery | A relation (which can contain multiple rows and columns) | Empty set (0 rows) | Anywhere a relation (set) is allowed |
Example (when t2 is empty, the two subqueries return different results):
-- Scalar subquery. When t2 is empty, the subquery returns the scalar value null.
select * from t1 where t1.c1 > (select sum(t2.c1) from t2);
-- Non-scalar subquery. When t2 is empty, the subquery returns an empty set (0 rows).
select * from t1 where t1.c1 in (select t2.c1 from t2);
Classification by whether outer columns are referenced
By whether the subquery references columns from the outer query, subqueries can be divided into correlated subqueries and uncorrelated subqueries.
| Type | References outer columns | Execution method |
|---|---|---|
| Uncorrelated subquery | No | Can usually be evaluated independently and returns its result once for use by the outer query. |
| Correlated subquery | Yes (commonly in the subquery's WHERE clause) | Its result logically depends on an outer row. The optimizer can decorrelate it into a join, so it does not necessarily execute once per row. |
Examples:
-- Correlated subquery. The subquery uses the outer table column t1.c2.
select * from t1 where t1.c1 in (select t2.c1 from t2 where t2.c2 = t1.c2);
-- Uncorrelated subquery. The subquery does not reference any column of the outer table t1.
select * from t1 where t1.c1 in (select t2.c1 from t2);
Supported subqueries
VeloDB Cloud supports uncorrelated scalar and relational subqueries. Correlated subqueries have additional restrictions:
- Correlated scalar subqueries in the
WHEREandHAVINGclauses are supported. - Correlated non-scalar subqueries with
IN,NOT IN,EXISTS, orNOT EXISTSin theWHEREandHAVINGclauses are supported. - Correlated scalar subqueries in the
SELECTlist are supported. - For nested subqueries, only correlation to the immediate parent query is supported. Cross-level correlation to a more outer query is not supported.
Limitations of correlated subqueries
Different forms of correlated subqueries have different limitations in VeloDB Cloud, described below.
Limitations of correlated scalar subqueries
In a future release, subqueries that contain set operations such as UNION, INTERSECT, or EXCEPT and reference outer columns will be explicitly rejected during analysis, for example with Unsupported correlated subquery with set operation. Uncorrelated set-operation subqueries are unaffected. A top-level EXISTS or NOT EXISTS over an ungrouped aggregate can still simplify to true or false when its result is known. This does not imply that all subqueries containing set operations are unsupported.
The correlation condition must use equality. Correlation below an aggregate with GROUP BY is rejected. A scalar subquery without aggregation is also supported, but it must return at most one row for each outer row. More complex combinations of joins, windows, limits, and outer references have additional analysis restrictions.
-- Single aggregate function and no group by: supported.
select * from t1 where t1.c1 < (select max(t2.c1) from t2 where t1.c2 = t2.c2);
-- The equivalent rewritten SQL:
select t1.* from t1 inner join (select t2.c2 as c2, max(t2.c1) as c1 from t2 group by t2.c2) tx on t1.c1 < tx.c1 and t1.c2 = tx.c2;
-- Non-equality correlation condition: not supported.
select * from t1 where t1.c1 = (select max(t2.c1) from t2 where t1.c2 > t2.c2);
-- Without aggregation: valid only when each outer row has at most one match.
select * from t1 where t1.c1 = (select t2.c1 from t2 where t1.c2 = t2.c2);
-- Aggregate function present but with group by: not supported.
select * from t1 where t1.c1 = (select max(t2.c1) from t2 where t1.c2 = t2.c2 group by t2.c2);
Limitations of correlated (NOT) EXISTS subqueries
- The subquery cannot use both
offsetandlimit.
-- With limit but without offset: supported.
select * from t1 where exists (select t2.c1 from t2 where t1.c2 = t2.c2 limit 2);
-- The equivalent rewritten SQL:
select * from t1 left semi join t2 on t1.c2 = t2.c2;
-- With both offset and limit: not supported.
select * from t1 where exists (select t2.c1 from t2 where t1.c2 = t2.c2 limit 2, 3);
Limitations of correlated (NOT) IN subqueries
The following three conditions must be met at the same time:
- The subquery output must be a single column.
- The subquery cannot use
limit. - The subquery cannot use aggregate functions or a
group byclause.
-- Supported subquery.
select * from t1 where t1.c1 in (select t2.c1 from t2 where t1.c2 = t2.c2);
-- The equivalent rewritten SQL:
select * from t1 left semi join t2 on t1.c1 = t2.c1 and t1.c2 = t2.c2;
-- Multi-column output in the subquery: not supported.
select * from t1 where (t1.a, t1.c) in (select t2.c1, t2.c from t2 where t1.c2 = t2.c2);
-- Subquery with limit: not supported.
select * from t1 where t1.c1 in (select t2.c1 from t2 where t1.c2 = t2.c2 limit 3);
-- With a group by clause: not supported.
select * from t1 where t1.c1 in (select t2.c1 from t2 where t1.c2 = t2.c2 group by t2.c1);
-- With an aggregate function: not supported.
select * from t1 where t1.c1 in (select sum(t2.c1) from t2 where t1.c2 = t2.c2);
Limitations of nested subqueries
Currently, only correlation between a subquery and its immediate parent query is supported. Correlation to a more outer query is not supported.
Assume there is also a t3 table, defined as follows:
create table t3
(
c1 bigint,
c2 bigint
)
DISTRIBUTED BY HASH(c1) BUCKETS 3;
-
Supported: the subquery references only columns from its immediate parent query.
selectt1.c1fromt1where not exists (selectt2.c1fromt2where not exists (selectt3.c1fromt3wheret3.c2 = t2.c2) and t2.c2 = t1.c2); -
Not supported: the innermost subquery references both
t2.c2from its immediate parent query andt1.c1from the outermost query.selectt1.c1fromt1where not exists (selectt2.c1fromt2where not exists (selectt3.c1fromt3wheret3.c2 = t2.c2 and t3.c1 = t1.c1));
Mark join
In a WHERE clause, when a (NOT) IN or (NOT) EXISTS subquery is combined with another filter condition through an OR relationship, special handling is required to produce a correct result. For example:
select
t1.c1,
t1.c2
from t1
where exists (
select
t2.c1
from t2
where
t1.c2 = t2.c2
) or t1.c1 > 0;
If the EXISTS clause above is rewritten directly as a LEFT SEMI JOIN, by its semantics only the rows in t1 satisfying t1.c2 = t2.c2 would be returned, but rows satisfying t1.c1 > 0 should also be returned. To handle this, VeloDB Cloud introduces the Mark Join mechanism.
Note:
RIGHT SEMI JOINis similar; only the left and right tables are swapped. The example here usesLEFT SEMI JOIN.
The example SQL is as follows:
-- This SQL cannot actually be executed. It is shown for illustration only.
select
tx.c1,
tx.c2
from
(
select
t1.c1,
t1.c2,
mark_join_flag
from
t1 left (mark) semi join t2 on t1.c2 = t2.c2
) tx
where
tx.mark_join_flag or tx.c1 > 0;
A regular LEFT SEMI JOIN filters out left rows without a match. A Mark Join retains the left rows and an internal flag for evaluating the original predicate. An EXISTS flag records whether a match exists. An IN predicate can also produce NULL under SQL three-valued logic. The following table illustrates one equality comparison, not the final flag for an entire right-side relation:
| t1.c2 | t2.c2 | Equality result |
|---|---|---|
| 1 | 1 | TRUE |
| 1 | 2 | FALSE |
| 1 | NULL | NULL |
NULL | 1 | NULL |
NULL | NULL | NULL |
The internal flag lets the optimizer preserve both branches of WHERE mark_join_flag OR t1.c1 > 0. Mark Join syntax and the flag are explanatory implementation details, not SQL you need to write.
FAQ
Because the output of a scalar subquery must be a single value, a runtime error is reported if the subquery returns more than one record.
Correlated scalar subquery returns multiple rows
When using a correlated scalar subquery, if for some outer row the subquery returns more than one row that matches the correlation condition, a runtime error is triggered.
-- Correlated scalar subquery. If more than one row in t2 satisfies t1.c2 = t2.c2, a runtime error is reported.
select t1.*, (select t2.c1 from t2 where t1.c2 = t2.c2) from t1;
-- Example error message:
ERROR 1105 (HY000): errCode = 2, detailMessage = (127.0.0.1)[INVALID_ARGUMENT][E33] correlate scalar subquery must return only 1 row
Uncorrelated scalar subquery returns multiple rows
VeloDB Cloud adds an assert num rows operator at runtime. If the subquery returns more than one record, a runtime error is triggered.
-- Uncorrelated scalar subquery. If t2 contains more than one row, a runtime error may be reported.
select t1.*, (select t2.c1 from t2) from t1;
-- Example error message:
ERROR 1105 (HY000): errCode = 2, detailMessage = (127.0.0.1)[CANCELLED]Expected EQ 1 to be returned by expression