Subqueries and CTEs · Lesson 52 of 64

SQL Subqueries in FROM

What you will learn

  • How to put a query in FROM (a derived table)
  • Why it needs an alias
  • How to aggregate an aggregate
  • How to join a summary back to the rows

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. A query as a table

FROM normally names a table. It can also hold a subquery in brackets, whose result acts as a temporary table. This derived table must have an alias:

SELECT status, orders
FROM (SELECT status, COUNT(*) AS orders FROM orders GROUP BY status) AS per_status
WHERE orders > 100
ORDER BY orders DESC;
status     orders
---------  ------
delivered    1878
shipped       231
paid          186
cancelled     170
pending       135
(5 rows)
SELECT status, accounts
FROM (SELECT status, COUNT(*) AS accounts FROM accounts GROUP BY status) AS per_status
WHERE accounts > 50
ORDER BY accounts DESC;
status  accounts
------  --------
open         404
(1 row)
SELECT term, sections
FROM (SELECT term, COUNT(*) AS sections FROM sections GROUP BY term) AS per_term
WHERE sections > 5
ORDER BY term;
term         sections
-----------  --------
2025-Autumn        14
2025-Spring        16
2026-Spring        11
(3 rows)

The inner query makes a small table of counts. The outer query then filters it with a plain WHERE on the alias orders, something a single level cannot do (HAVING could, but a derived table also lets you join, sort and re-aggregate).

2. Aggregating an aggregate

You cannot write AVG(COUNT(*)). But you can compute the counts in a derived table and average them outside:

Average number of orders per customer (customers with at least one order):

SELECT ROUND(AVG(orders), 2) AS avg_orders_per_customer, MAX(orders) AS most_orders
FROM (SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id) AS per_customer;
avg_orders_per_customer  most_orders
-----------------------  -----------
                   7.12           17
(1 row)

Average number of accounts per customer (customers with at least one account):

SELECT ROUND(AVG(accounts), 2) AS avg_accounts_per_customer, MAX(accounts) AS most_accounts
FROM (SELECT customer_id, COUNT(*) AS accounts FROM accounts GROUP BY customer_id) AS per_customer;
avg_accounts_per_customer  most_accounts
-------------------------  -------------
                     1.91              7
(1 row)

Average number of enrollments per student (students with at least one):

SELECT ROUND(AVG(enrollments), 2) AS avg_enrollments_per_student, MAX(enrollments) AS most_enrollments
FROM (SELECT student_id, COUNT(*) AS enrollments FROM enrollments GROUP BY student_id) AS per_student;
avg_enrollments_per_student  most_enrollments
---------------------------  ----------------
                       2.95                 8
(1 row)

3. Join a summary back to the rows

A derived table can be joined like any table. Here each row gets its group's total next to it:

SELECT p.name, p.price, c.avg_price
FROM products AS p
JOIN (SELECT category_id, ROUND(AVG(price), 2) AS avg_price FROM products GROUP BY category_id) AS c
  ON c.category_id = p.category_id
ORDER BY p.product_id
LIMIT 4;
name              price  avg_price
----------------  -----  ---------
Steel pan           6.6       31.5
Ceramic mug        44.1       31.5
Wooden spoon set   29.5       31.5
Glass jar           5.4       31.5
(4 rows)
SELECT a.account_id, a.balance_cents, b.avg_balance
FROM accounts AS a
JOIN (SELECT branch_id, CAST(AVG(balance_cents) AS INTEGER) AS avg_balance FROM accounts GROUP BY branch_id) AS b
  ON b.branch_id = a.branch_id
ORDER BY a.account_id
LIMIT 4;
account_id  balance_cents  avg_balance
----------  -------------  -----------
         1         192400       130962
         2          52078       127844
         3          62780       142899
         4          99900       130962
(4 rows)
SELECT c.code, c.credits, d.avg_credits
FROM courses AS c
JOIN (SELECT department_id, ROUND(AVG(credits), 2) AS avg_credits FROM courses GROUP BY department_id) AS d
  ON d.department_id = c.department_id
ORDER BY c.course_id
LIMIT 4;
code     credits  avg_credits
-------  -------  -----------
MATH101        4         3.67
MATH201        3         3.67
MATH301        4         3.67
SCI101         4         3.75
(4 rows)

This does the same job as the correlated subquery of lesson 7.3, but the summary is computed once per group, not once per row.

4. Top rows of a summary

Rank groups, then keep the best: sort and limit in the derived table, then work on those rows:

SELECT c.name AS category, t.products
FROM (SELECT category_id, COUNT(*) AS products FROM products GROUP BY category_id ORDER BY products DESC, category_id LIMIT 3) AS t
JOIN categories AS c ON c.category_id = t.category_id
ORDER BY t.products DESC, c.name;
category    products
----------  --------
Kitchen            7
Stationery         7
Toys               7
(3 rows)
SELECT b.name AS branch, t.accounts
FROM (SELECT branch_id, COUNT(*) AS accounts FROM accounts GROUP BY branch_id ORDER BY accounts DESC, branch_id LIMIT 3) AS t
JOIN branches AS b ON b.branch_id = t.branch_id
ORDER BY t.accounts DESC, b.name;
branch     accounts
---------  --------
Central          87
Riverside        79
Airport          76
(3 rows)
SELECT d.name AS department, t.courses
FROM (SELECT department_id, COUNT(*) AS courses FROM courses GROUP BY department_id ORDER BY courses DESC, department_id LIMIT 3) AS t
JOIN departments AS d ON d.department_id = t.department_id
ORDER BY t.courses DESC, d.name;
department   courses
-----------  -------
Science            4
Languages          3
Mathematics        3
(3 rows)

Summarising first and joining the names afterwards also keeps the GROUP BY simple.

5. Derived table, view or WITH

Tool Best for
derived table a one-off step inside one query
WITH (lesson 7.5) the same, but named and read top to bottom
view (lesson 6.7) a step used by many queries

Nested derived tables get hard to read after two levels. That is the moment to switch to WITH.

Worked example: customers above the average spend

Step Query
1 per customer: SELECT customer_id, SUM(amount) AS spent FROM payments_per_customer GROUP BY customer_id
2 the average of those totals: SELECT AVG(spent) FROM (step 1) AS s
3 customers whose spent is above step 2

Step 1 is a derived table inside step 2; in lesson 7.6 the same steps are written as a chain of WITH queries. The table names are made up.

Common mistakes

  • Forgetting the alias on the derived table.
  • Not naming the computed columns in the inner query, so the outer query cannot use them.
  • Nesting three or four levels deep.
  • Re-running the same derived table several times in one statement.

Key takeaways

  • A subquery in FROM is a temporary table and needs an alias.
  • Name the inner columns so the outer query can use them.
  • It lets you aggregate an aggregate and join a summary back to the rows.
  • When it nests deeper than two levels, use WITH.

Practice

1. What must a subquery in FROM have?

Show answer

An alias.

2. How do you get the average of per-customer order counts?

Show answer

Count the orders per customer in a derived table, then AVG that column in the outer query.

3. Why alias the computed columns of the inner query?

Show answer

The outer query refers to them by name.

4. How is a joined derived table different from a correlated subquery?

Show answer

The summary is computed once per group and then joined, not once per outer row.

5. Where do ORDER BY ... LIMIT 3 go to keep the top three groups?

Show answer

Inside the derived table, after its GROUP BY.

6. When should you switch from nested subqueries to WITH?

Show answer

When the nesting is more than about two levels deep and hard to read.