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.