PostgreSQL Subqueries
Overview
Subqueries are queries nested inside other SQL queries. They can appear in WHERE, FROM, SELECT clauses and can return single values, single rows, or multiple rows. Subqueries enable complex data retrieval logic to be completed in a single SQL statement.
WHERE Subqueries
IN Subquery
IN checks if a value exists in the result set returned by the subquery:
NOT IN Subquery
NOT IN excludes values in the subquery result:
When the subquery result contains NULL values, NOT IN will return an empty result set. Use NOT EXISTS instead.
EXISTS Subquery
EXISTS checks if the subquery returns at least one row:
NOT EXISTS Subquery
NOT EXISTS checks if the subquery returns no data:
ANY / SOME Subquery
ANY (or SOME) compares a value with any value returned by the subquery. The condition is true if it matches at least one value:
ALL Subquery
ALL compares a value with all values returned by the subquery. The condition must be true for all values:
FROM Subqueries (Derived Tables)
Subqueries can be placed in the FROM clause as temporary tables (also called derived tables or inline views):
Subqueries in the FROM clause must be aliased using AS.
SELECT Subqueries (Scalar Subqueries)
Subqueries can be placed in the SELECT clause as computed columns. In this case, the subquery must return a single value (scalar value):
Correlated Subqueries
A correlated subquery references columns from the outer query. The subquery is re-executed for each row processed by the outer query:
Summary
Subquery key points:
WHEREclause can useIN,EXISTS,ANY,ALLoperators- Subqueries in
FROMclause are used as derived tables and must be aliased - Scalar subqueries in
SELECTclause are used for computed columns and must return a single value - Correlated subqueries reference outer query columns and are re-executed for each row
NOT INhas special behavior withNULLvalues; preferNOT EXISTS