subquery: A query nested inside another — in SELECT, FROM, or WHERE. A correlated subquery references the outer row. A subquery is a query inside another query. It can appear in WHERE, as in finding customers whose total exceeds the average, in FROM as a derived table, or in SELECT to calculate a value per row.
A correlated subquery refers to the outer query's current row, such as counting each customer's orders. It runs once per outer row, which can be slow on large tables.
What should you keep in mind with subquery?
Modern databases optimise many subqueries well, but when one is slow, rewriting it as a JOIN, a CTE or a window function often helps. EXISTS subqueries are an efficient exception, because they stop at the first match. Check with EXPLAIN rather than guessing. For readability, a CTE with a clear name is often easier to follow than deeply nested subqueries.
What does an example of subquery look like?
SELECT name FROM users u WHERE (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) > 0;