Sub topic 3
Derived tables: subqueries in FROM
This chapter assumes you know SELECT, WHERE, GROUP BY, INNER JOIN and LEFT JOIN, and how NULL behaves. Examples use PostgreSQL syntax unless noted.
A derived table is a subquery in the FROM clause. The database runs the inner SELECT, treats its result as a temporary table, and gives it an alias. Most databases require the alias.
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. The outer query joins that result to departments.
CTEs as named, readable subqueries
A common table expression (CTE) is a named query defined with WITH before the main query. It holds the same logic as a derived table but reads top to bottom.
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;Use a CTE when you need the same intermediate result in several places, or when nested subqueries get hard to follow.
Subqueries in UPDATE and DELETE
Data-modifying statements can filter rows with a subquery.
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE status = 'closed'
);Subquery or join?
A join is usually clearer when the result needs columns from both tables. A subquery fits a filter, such as "rows that have a match." An inner join can repeat a row when the joined table has several matches. An IN subquery returns each outer row at most once.
Lateral subqueries for per-row subselects
A LATERAL subquery can refer to columns of the tables before it. The database runs it once for each outer row. This query returns each customer's largest order. PostgreSQL and MySQL 8.0.14 or later support it. SQLite does not.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE customer_id = c.id
ORDER BY total DESC
LIMIT 1
) AS o;Performance and query plans
Run EXPLAIN before the query to see the plan. In PostgreSQL, EXPLAIN ANALYZE also runs the query and shows real timings. Watch for a sequential scan on a large table, and for a SubPlan that runs once per row.
> Hmm, nothing here.
Exercise
Rewrite the derived table query above so the aggregate is a CTE named dept_avg.
Show answer
WITH deptavg AS (SELECT departmentid, AVG(salary) AS avgsalary FROM employees GROUP BY departmentid) SELECT d.name, s.avgsalary FROM departments d JOIN deptavg s ON s.department_id = d.id;