A subquery is a SELECT statement nested inside another SQL statement to provide a derived set of rows or a single value.
A subquery is an inner SELECT that supplies a value set to an outer query. PostgreSQL evaluates the inner query first, then feeds the result to the outer query.
Subqueries shine when the derived rows need further aggregation, when filtering on aggregated values, or when readability outweighs performance. For simple row combinations, a JOIN is usually faster.
Place the inner SELECT inside parentheses. It can appear in the SELECT list, FROM clause, or WHERE clause. Use aliases to reference subquery columns.
Use WHERE column IN (SELECT ...) or EXISTS (SELECT 1 FROM ... WHERE ...). PostgreSQL returns only rows matching the inner query conditions.
Wrap an aggregate SELECT in the FROM clause, give it an alias, then join or filter on the aggregated columns. This isolates aggregation logic from the outer query.
Index columns referenced in correlated subqueries, alias everything, and limit the returned columns to reduce planning time. Consider WITH queries (CTEs) for clarity.
Returning multiple columns where one is expected, or forgetting to correlate the subquery, both cause errors or unintended Cartesian products.
Often yes, because PostgreSQL may execute the subquery for every outer row. However, planner optimizations and indexes can mitigate the cost.
Use EXISTS for correlated subqueries and IN for small, static result sets. EXISTS stops scanning once it finds a match, which can be faster.
Yes. Use UPDATE ... SET column = (SELECT ...) or UPDATE ... FROM (SELECT ...) pattern to modify rows based on subquery results.