diff --git a/docs/doc/30-reference/30-sql/30-query-operators/operators-subquery.md b/docs/doc/30-reference/30-sql/30-query-operators/operators-subquery.md index fc1bb7be7e66..794e39e23917 100644 --- a/docs/doc/30-reference/30-sql/30-query-operators/operators-subquery.md +++ b/docs/doc/30-reference/30-sql/30-query-operators/operators-subquery.md @@ -4,11 +4,47 @@ description: A subquery is a query nested within another query. --- -This topic provides reference information about the subquery operators supported in Databend. +A subquery is a query nested within another one. Databend supports the following subquery types: -A subquery is a query nested within another query. +- [Scalar Subquery](#scalar-subquery) +- [EXISTS / NOT EXISTS](#exists--not-exists) -## [ NOT ] EXISTS +## Scalar Subqueries + +A scalar subquery selects only one column or expression and returns only one row at most. A SQL query can have scalar subqueries in any places where a column or expression is expected. + +- If a scalar subquery returns 0 rows, Databend will use NULL as the subquery output. +- If a scalar subquery returns more than one row, Databend will throw an error. + +### Example + +```sql +CREATE TABLE t1 (a int); +CREATE TABLE t2 (a int); + +INSERT INTO t1 VALUES (1); +INSERT INTO t1 VALUES (2); +INSERT INTO t1 VALUES (3); + +INSERT INTO t2 VALUES (3); +INSERT INTO t2 VALUES (4); +INSERT INTO t2 VALUES (5); + +SELECT * +FROM t1 +WHERE t1.a < (SELECT Min(t2.a) + FROM t2); + +-- ++--------+ +| a | ++--------+ +| 1 | +| 2 | ++--------+ +``` + +## EXISTS / NOT EXISTS An EXISTS subquery is a boolean expression that can appear in a WHERE clause: * An EXISTS expression evaluates to TRUE if any rows are produced by the subquery.