← All lessons
Advanced SQL · Lesson 11 of 11

Putting it all together

Real questions rarely say which feature to use. This lesson is practice in working that out. For each problem, before writing anything, ask three things: what does one row of the answer stand for, which tables hold the facts, and what has to happen in what order. Then build it a step at a time with CTEs, checking each step's rows.

Worked example: the second-highest salary. Two common answers. Take the largest salary below the largest:

SELECT MAX(salary) AS second_highest
FROM staff
WHERE salary < (SELECT MAX(salary) FROM staff);
Returns
second_highest
--------------
62000
(1 row)

Or rank the distinct salaries and pick rank 2, which generalises to "the Nth" and to "in each department" with a PARTITION BY:

WITH r AS (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM staff
)
SELECT DISTINCT salary FROM r WHERE rnk = 2;
Returns
salary
------
62000
(1 row)

Worked example: customers all of whose orders shipped. "All" questions are easiest turned round: keep the customers with no order that isn't shipped. Or count: customers whose number of shipped orders equals their number of orders.

SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
HAVING SUM(CASE WHEN o.status = 'shipped' THEN 1 ELSE 0 END) = COUNT(*)
ORDER BY c.name;
Returns
name
----
Ana
Ben
Dev
Finn
(4 rows)

Note the JOIN rather than a LEFT JOIN: customers with no orders at all would pass "none of their orders failed" too, and whether they should is a question to ask whoever wanted the report. Edge cases like that, ties, NULLs and empty groups, are what interviewers listen for. Say them out loud.

Practice

The third-highest distinct salary in staff. One number.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

Nth highestDENSE_RANK() OVER (ORDER BY x DESC) = n.
"all" questionsTurn round (none that fail) or compare counts with HAVING.
pairsSelf join with a.id < b.id.
change over timeAggregate per period, then LAG.
share of totalx / SUM(x) OVER ().

The other AI and data engineering courses