Subquery
Subquery is a query nested inside another query. In SQL, the inner query is evaluated to supply values to the outer query. Subqueries can appear in the SELECT list, the FROM clause, or the WHERE and HAVING clauses, and they can return a single value, a single row, or a set of rows.
Scalar subquery: returns a single value; used in a WHERE condition or in a select. Example: SELECT
Table subquery (set): returns multiple rows; commonly used with IN or EXISTS or as derived table in
Correlated subquery: inner query references columns from the outer query; executed once per outer row; often
Non-correlated subquery: inner query does not reference outer query; can be evaluated once.
Derived table: subquery in FROM clause; acts as a temporary table. Example: SELECT t.product_id, t.total FROM
Uses and limitations: Some databases require scalar subqueries to return exactly one row and one column; otherwise