Sub topic 1
What a Subquery Is and Where It Can Appear
A subquery is a SELECT statement nested inside another SQL statement. The outer statement uses the subquery's result as if it were a value, a list of values, or a table. This chapter gives the working model: what a subquery returns, where it can be placed, and the errors you meet first. Later chapters cover each form in detail.
Prerequisites
This chapter assumes you can already do the following:
- Write
SELECT,WHERE, andORDER BYclauses. - Use aggregate functions such as
AVG,COUNT, andMAX, and group rows withGROUP BY. - Combine tables with
INNER JOINandLEFT JOIN. - Explain what
NULLmeans and how three-valued logic works (a comparison can be true, false, or unknown).
The examples use two tables. employees has the columns id, name, salary, and department_id. departments has id and name. A customers table (id, name, status) and an orders table (id, customer_id, total) appear in some examples.
The Working Model
Many questions have layers. "Who earns more than the average salary?" needs two steps: first compute the average, then compare each employee to it. A subquery lets you write both steps in one statement.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);The part in parentheses is the inner query (the subquery). The rest is the outer query. Conceptually, the database evaluates the inner query first, gets one number, and then runs the outer query with that number in place of the parentheses.
Three rules define a subquery:
- It is a complete
SELECTstatement. - It is enclosed in parentheses.
- Its result is used by the outer statement as a scalar value, a list, or a table.
The shape of the result decides where the subquery is allowed. That is the main idea of this chapter.
The Three Result Shapes
Every subquery produces a result set with some number of rows and columns. The outer statement needs a particular shape, depending on where the subquery sits.
| Shape | Rows and columns | Typical use |
|---|---|---|
| Scalar | Exactly one row, one column | Compare with `=`, `>`, `<`, or place in the `SELECT` list |
| Column (list) | Any number of rows, one column | `IN`, `NOT IN`, `ANY`, `ALL` |
| Table | Any rows, any columns | In the `FROM` clause as a derived table |
A fourth use, EXISTS, ignores the columns and asks only whether any row came back.
Scalar results
A scalar subquery returns one row and one column. The average example above is scalar because an aggregate without GROUP BY always yields one row.
If a scalar subquery returns more than one row, most databases raise an error. PostgreSQL reports "more than one row returned by a subquery used as an expression". If it returns zero rows, the result is NULL, and a comparison with NULL is unknown, so no rows match.
Column results
A subquery that returns one column and many rows can feed IN:
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 100);The inner query returns a list of customer ids. IN keeps customers whose id appears in that list. If the subquery selected two columns, the database would reject it with a column-count error, because id is being compared to a single value.
Table results
A subquery in the FROM clause behaves as a temporary table, called a derived table:
SELECT d.name, s.avg_salary
FROM departments 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 returns several rows and columns. The outer query joins to it using the alias s.
Where a Subquery Can Appear
The diagram shows the main positions. Each is covered in its own chapter later.
In WHERE and HAVING
This is the most common position. The subquery supplies a value or list to a predicate (a condition). Forms include comparison operators, IN, ANY, ALL, and EXISTS. HAVING works the same way for conditions on groups.
In FROM
The subquery acts as a table and must have an alias in most databases. PostgreSQL, for example, requires one in older versions and MySQL always does. The columns of the derived table are available to the outer query under that alias.
In the SELECT list
A subquery here must be scalar, because each output row needs exactly one value in that column:
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;This inner query refers to c.id from the outer query. That makes it a correlated subquery, which is the topic of a later chapter. Note that customers with no orders get 0, because COUNT(*) over zero rows is 0.
In UPDATE and DELETE
Data-modifying statements can use subqueries to decide which rows to change:
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);The same works in the WHERE clause of UPDATE, and in the SET clause when the subquery is scalar. Some databases restrict reading from the table you are modifying. MySQL, for instance, rejects a subquery on the target table in a DELETE unless you wrap it in a derived table.
Independent and Correlated Subqueries
There is one more distinction that affects how you read any subquery.
- An independent (uncorrelated) subquery makes no reference to the outer query. It could run alone. Every example so far in the
WHEREandFROMpositions is independent, and the database can compute it once. - A correlated subquery refers to a column of the outer query. It cannot run alone, and conceptually it is evaluated once per outer row.
A quick test: copy the inner query into a separate window and run it. If it fails with "unknown column", it is correlated.
Scoping Rules and Aliases
Names inside a subquery are resolved in a fixed order. The database looks for a column in the subquery's own tables first, then in the enclosing query. The reverse does not hold: the outer query cannot see columns that exist only inside the subquery.
This causes a common silent error. Consider:
SELECT name
FROM customers
WHERE id IN (SELECT id FROM orders WHERE total > 100);This runs without error, but id in the subquery is orders.id, the order's own id, not a customer id. The query compares customer ids to order ids and returns wrong rows. Writing SELECT customer_id fixes it. The mistake is worse when the column name you meant is missing from the inner table: the name then resolves to the outer table and the subquery becomes accidentally correlated.
The defense is to qualify column names with table aliases whenever a subquery is present:
SELECT c.name
FROM customers c
WHERE c.id IN (SELECT o.customer_id FROM orders o WHERE o.total > 100);When two levels use the same table, as in the average-per-department query, give each its own alias (e and e2) so the reference is unambiguous.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Subquery returns more than 1 row" | A scalar position received several rows | Use `IN`, `ANY`, or an aggregate, or add a filter that guarantees one row |
| "Operand should contain 1 column(s)" or similar | The subquery selected several columns where one is expected | Select a single column |
| "Every derived table must have its own alias" | Missing alias in `FROM` | Add `AS name` after the closing parenthesis |
| Query returns no rows when you expect some | A scalar subquery returned no rows, so the comparison is unknown | Test the subquery alone, and check for `NULL` |
| Right syntax, wrong rows | A column name resolved to the wrong table | Qualify every column with an alias |
Subqueries and Other Constructs
Subqueries are not the only way to layer a question. Joins combine tables side by side. Common table expressions (CTEs, introduced with WITH) give a subquery a name and move it above the main query. Both are covered in later chapters, along with how to choose between them. For now, treat the subquery as the general tool: any SELECT can be nested wherever the outer statement accepts a value, a list, or a table.
A subquery can also contain subqueries. SQL allows nesting several levels deep, and the same rules apply at each level. In practice, more than two levels is hard to read, which is the usual reason to switch to a CTE.
Summary
- A subquery is a parenthesized
SELECTinside another statement. - Its result shape (scalar, column, or table) must match what the position expects.
- Subqueries can appear in
WHERE,HAVING,FROM, theSELECTlist, and theWHEREorSETofUPDATEandDELETE. - Independent subqueries can run alone. Correlated ones refer to the outer row.
- Qualify column names with aliases, since an unqualified name can silently resolve to the wrong table.
Exercise
The query below runs without error but returns the wrong customers. Explain why, and rewrite it correctly. SELECT name FROM customers WHERE id IN (SELECT id FROM orders WHERE total > 100);
Show answer
In the subquery, the unqualified id resolves to orders.id, the order's own key, so the query compares customer ids to order ids. The subquery should return customer_id. Corrected: SELECT c.name FROM customers c WHERE c.id IN (SELECT o.customer_id FROM orders o WHERE o.total > 100);
Exercise
For each position, state the result shape the subquery must return: (a) the right side of salary > (...), (b) the list in id IN (...), (c) a subquery in FROM, (d) a subquery in the SELECT list.
Show answer
(a) Scalar: one row, one column. (b) A column: one column, any number of rows. (c) A table: any rows and columns, with an alias. (d) Scalar: one row, one column.
Exercise
How can you tell whether a subquery is correlated without reading the whole statement?
Show answer
Run the inner query alone. If it fails because it refers to a column that exists only in the outer query, it is correlated. If it runs on its own, it is independent.