Sub topic 1
SQL Subqueries: What a Subquery Is and Where It Can Appear
A subquery is a SELECT statement nested inside another SQL statement. The inner query produces a result that the outer query uses. This lets you answer a layered question in one statement.
For example, “Which employees earn more than the company average?” has two parts:
- Calculate the average salary.
- Find employees whose salary is greater than that value.
Prerequisites
This chapter assumes that you can write basic SELECT, WHERE, and ORDER BY clauses. You should also know aggregate functions such as AVG, COUNT, and MAX, GROUP BY, inner and left joins, and the meaning of NULL.
The basic structure
A subquery is enclosed in parentheses. The outer query treats its result as a value, a list, or a temporary table, depending on where the subquery appears.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The inner query returns one value: the average salary. The outer query compares each employee's salary with that value.
A subquery can appear in several locations:
| Location | What the subquery provides | Typical use |
|---|---|---|
| `WHERE` | A value or set of values | Filter rows |
| `FROM` | A temporary result table | Organize intermediate calculations |
| `SELECT` | A value for each output row | Add a calculated column |
| `UPDATE` or `DELETE` | Values used by the modification | Change or remove selected rows |
A subquery in a WHERE clause is often the easiest form to read. The inner query answers a smaller question, and the outer query applies the result.
Subqueries in `WHERE`
The result shape must match the operator. A subquery that returns one value can work with =, >, or <. A subquery that returns several values commonly works with IN.
SELECT name
FROM customers
WHERE id IN (
SELECT customer_id
FROM orders
WHERE total > 100
);The inner query returns customer IDs for orders over 100. The outer query returns customers whose IDs occur in that list.
A subquery may return no rows. For a comparison with a scalar subquery, this can produce NULL or an unknown result, depending on the database system. Check the expected result shape before choosing an operator.
Subqueries in `FROM`
A subquery in FROM is called a derived table. It creates an intermediate result that the outer query can join or filter. Every derived table needs an alias.
SELECT d.name, s.avg_salary
FROM departments AS d
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS s
ON s.department_id = d.id;Here, the inner query calculates one average for each department. The outer query attaches department names to those averages.
Subqueries in the `SELECT` list
A subquery can also calculate one value for each output row.
SELECT c.name,
(SELECT COUNT(*)
FROM orders AS o
WHERE o.customer_id = c.id) AS order_count
FROM customers AS c;The inner query counts orders for the current customer. This form is useful when the calculated value belongs directly in the result columns. The reference to c.id makes this a correlated subquery. The next chapters examine correlated subqueries and their alternatives in more detail.
Exercise
Where can a subquery appear, and what does a subquery in FROM require?
Show answer
It can appear in WHERE, FROM, the SELECT list, and data-modifying statements such as UPDATE or DELETE. A subquery in FROM is a derived table and requires an alias.