Sub topic 9
Derived Tables: Subqueries in `FROM`
A derived table is a subquery in the FROM clause. It produces a temporary result set that the outer query can treat like a table. The derived table exists only while the statement runs.
This chapter assumes you know SELECT, WHERE, ORDER BY, aggregate functions, GROUP BY, and inner and left joins. You should also understand that NULL represents an unknown or missing value.
Build an intermediate result
Suppose employees contains one row per employee. To calculate the average salary for each department, first group the employees:
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;This query returns one row per department. Place it in FROM, and the outer query can join those results to departments:
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;The subquery is the derived table. The alias s is required by many SQL databases and is good practice everywhere. The outer query sees s.department_id and s.avg_salary as if they were columns in a regular table.
A derived table is useful when the question has two stages:
- Calculate an intermediate result.
- Filter, join, or sort that result.
For example, to find employees paid above their department average, calculate the averages first and then join them:
SELECT e.name, e.salary, da.avg_salary
FROM employees AS e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS da
ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;The inner query groups rows before the outer query compares individual employees with the grouped result.
Scope and common errors
A derived table has its own scope. The outer query cannot refer to columns that the inner query did not select. If the outer query needs department_id, the derived table must include it.
Column names can also become unclear when several tables have the same name. Use aliases and qualify columns:
SELECT e.name, da.avg_salary
FROM employees AS e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS da
ON e.department_id = da.department_id;A derived table does not automatically preserve rows from the outer table. An inner JOIN removes employees whose department has no matching average. Use LEFT JOIN when employees without a matching derived row must remain.
Derived tables and CTEs
A common table expression, or CTE, gives the intermediate query a name before the main query:
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
)
SELECT e.name, e.salary, da.avg_salary
FROM employees AS e
JOIN dept_avg AS da
ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;A derived table keeps the intermediate query beside its use. A CTE usually reads more clearly when the intermediate result is complex or when several later parts of the statement use it. Neither choice guarantees better performance. The database optimizer may transform both forms into the same plan.
> callout tip > Use a derived table when the intermediate result is short and used once. Use a CTE when naming the result makes a multi-step query easier to read.
Exercise
Why must the derived table in the department-average example select department_id as well as AVG(salary)?
Show answer
The outer query needs department_id to match each average to the correct employee or department. Columns not selected by the derived table are unavailable outside it.