Sub topic 9
Derived Tables: Subqueries in FROM
A derived table is a subquery placed in the FROM clause. The database runs it first, treats its result as a temporary table, and lets the outer query read from it. This chapter covers the syntax, the rules that trip people up, and the cases where a derived table is the right tool.
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, aggregate functions with GROUP BY, INNER JOIN and LEFT JOIN, and how NULL behaves in comparisons. The examples use employees (id, name, salary, department_id), departments (id, name), customers, and orders.
What a derived table is
In earlier chapters the subquery sat inside WHERE and produced a value or a list of values. In FROM the subquery produces a whole result set with rows and named columns. The outer query can then join it, filter it, or aggregate it like any other 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;The inner query returns one row per department with two columns, department_id and avg_salary. The outer query names that result s and joins it to departments to attach each department's name.
This is a logical model. The optimizer may rewrite the query, for example by merging the derived table into the outer query, as long as the result stays the same.
The rules for derived tables
An alias is required
Most databases, including PostgreSQL (before version 16), MySQL, and SQL Server, reject a derived table without an alias. The alias is how the outer query refers to the columns.
-- Fails in most databases: "Every derived table must have its own alias"
SELECT *
FROM (SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id);Add AS s after the closing parenthesis and the query runs. Always alias derived tables, even where your database allows omitting it, so the query stays portable.
Every column needs a usable name
The outer query sees only the column names the inner query exposes. An expression like AVG(salary) has no reliable name, so give it one with AS. Two columns with the same name in one derived table also cause errors or ambiguity. Rename them in the inner query.
The inner query is not visible to the outside
The aliases and columns inside the derived table exist only for the outer query. You cannot reference s.avg_salary from a different, unrelated statement. Nor can you reuse the same derived table twice in one query without writing it twice. Section "CTEs" below shows the fix.
Ordinary derived tables cannot see sibling tables
A plain derived table cannot refer to other tables in the same FROM clause. This fails:
-- Error: c is not visible inside the derived table
SELECT c.name, o.total
FROM customers c
JOIN (SELECT total FROM orders WHERE customer_id = c.id) AS o ON TRUE;If you need that behavior, use a LATERAL subquery, covered in a later chapter. Otherwise, move the correlation into the join condition, as the first example does.
Why use a derived table
Derived tables solve problems where one level of processing is not enough. Three situations come up repeatedly.
- Aggregate first, then join. You want per-group statistics next to row-level data. Aggregating inside the derived table keeps
GROUP BYfrom collapsing the outer rows. - Filter on an aggregate or computed value by name.
WHEREcannot see aSELECTalias or an aggregate result in the same query block. A derived table turns that value into an ordinary column that the outerWHEREcan use. - Layer calculations. You compute something, then compute something else from it, and each step stays readable.
Aggregate first, then join
To list each employee next to the average salary of their department, aggregate in a derived table and join it back.
SELECT e.name, e.salary, s.avg_salary,
e.salary - s.avg_salary AS diff
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS s ON s.department_id = e.department_id;Without the derived table you would need a window function or a correlated subquery in the SELECT list. The derived table runs the aggregation once, and the join attaches the result to every employee in that department.
Filter on a computed value
Suppose you want customers whose order count is at least 5. You can use HAVING, but a derived table lets you combine the filter with other logic, such as a join to more tables.
SELECT c.name, t.order_count
FROM customers c
JOIN (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS t ON t.customer_id = c.id
WHERE t.order_count >= 5
ORDER BY t.order_count DESC;Here order_count is a real column of t, so the outer WHERE can filter on it directly. Trying WHERE order_count >= 5 against an alias defined in the same SELECT fails in most databases, because WHERE is evaluated before the SELECT list.
Layer calculations
A derived table can feed another derived table, but nesting more than two levels quickly becomes hard to read. The next section covers the better option.
Derived tables and NULL
A derived table behaves like any table with respect to NULL. Aggregates ignore NULL inputs. AVG(salary) averages only the non-null salaries, and COUNT(column) counts only non-null values, while COUNT(*) counts rows.
Joining to a derived table with an INNER JOIN drops outer rows that have no match. Employees with a NULL department_id will vanish from the earlier per-department example, because NULL = NULL is not true. To keep unmatched rows, use LEFT JOIN and handle the resulting NULLs.
SELECT c.name, COALESCE(t.order_count, 0) AS order_count
FROM customers c
LEFT JOIN (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS t ON t.customer_id = c.id;Customers with no orders have no row in t, so the left join gives them NULL, and COALESCE turns that into 0.
From derived table to CTE
A common table expression (CTE) names the same subquery and places it above the main query with WITH. The logic does not change.
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 e
JOIN dept_avg da ON da.department_id = e.department_id
WHERE e.salary > da.avg_salary;This reads top to bottom: first define dept_avg, then use it. A CTE has two practical advantages over an inline derived table.
- You can reference it more than once in the same statement, so the logic is written once.
- A chain of steps reads as a list of named stages instead of parentheses nested inside parentheses.
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
),
overall AS (
SELECT AVG(avg_salary) AS company_avg
FROM dept_avg
)
SELECT da.department_id, da.avg_salary, o.company_avg
FROM dept_avg da
CROSS JOIN overall o
WHERE da.avg_salary > o.company_avg;Here overall builds on dept_avg, and the final query uses both. Written with derived tables, dept_avg would appear twice.
A single-use derived table and a single-use CTE usually produce the same plan. Choose the one that is easier for the next reader to follow.
Edge cases and gotchas
ORDER BYinside a derived table is not reliable. A derived table is a set of rows, and sets have no order. Many databases ignore the innerORDER BY, and SQL Server rejects it unless you also useTOPorOFFSET. Put theORDER BYin the outer query. The exception isORDER BYcombined withLIMIT, which selects which rows survive.- Row multiplication. If the derived table has several rows per join key, the join repeats outer rows. The per-department example is safe because
GROUP BY department_idguarantees one row per department. Check that the key you join on is unique in the derived table. - Aggregating after joining versus before. Joining
customerstoordersand then summing a customer-level column counts that column once per order. Aggregatingordersin a derived table first, then joining, avoids the inflated totals. - Performance. Some databases materialize a derived table, meaning they compute it in full and store it temporarily. Others merge it into the outer query. A derived table that returns millions of rows before a selective outer filter can be slow. Check the query plan, which a later chapter covers, rather than assuming.
- Name resolution. Column names inside the derived table can shadow nothing outside it, but
SELECT *from a derived table that joins two tables with anidcolumn in each produces a duplicate-name problem. List the columns explicitly.
Choosing a derived table
| Situation | Derived table or CTE helps? |
|---|---|
| Need a per-group aggregate next to row-level data | Yes, aggregate inside and join |
| Need to filter on an aggregate with extra joins or logic | Yes, the value becomes a normal column |
| Need the same intermediate result twice | Yes, use a CTE |
| Only need a single value to compare | No, use a scalar subquery in `WHERE` |
| Only need to test whether related rows exist | No, use `EXISTS` |
| Inner query must reference a sibling table in `FROM` | Not a plain derived table; use `LATERAL` |
Exercise
Write a query that returns each department's name and the number of employees in it, including departments with no employees (count 0). Use a derived table for the counts. Why is a LEFT JOIN needed, and why do you need COALESCE?
Show answer
SELECT d.name, COALESCE(t.empcount, 0) AS empcount FROM departments d LEFT JOIN ( SELECT departmentid, COUNT(*) AS empcount FROM employees GROUP BY departmentid ) AS t ON t.departmentid = d.id; The derived table has a row only for departments that have employees. An INNER JOIN would drop empty departments, so LEFT JOIN keeps them. For those departments t.emp_count is NULL, and COALESCE converts it to 0.
Exercise
This query fails in most databases. Name two problems and fix them. SELECT departmentid, AVG(salary) FROM (SELECT departmentid, salary FROM employees WHERE salary > 0) WHERE AVG(salary) > 50000;
Show answer
First, the derived table has no alias, so add AS s after the closing parenthesis. Second, an aggregate cannot appear in WHERE, and the query also lacks GROUP BY. Fix: SELECT departmentid, AVG(salary) AS avgsalary FROM (SELECT departmentid, salary FROM employees WHERE salary > 0) AS s GROUP BY departmentid HAVING AVG(salary) > 50000;