A billing dashboard shows the runner-up invoice as a sanity check against the largest one.
From invoices, return a single column second_highest_amount containing the second highest distinct amount. If fewer than two distinct amounts exist the query should return NULL rather than no rows.
Sample data
Table: invoices
12 row(s) · showing first 8
| invoice_idINT | account_codeTEXT | issued_onDATE | amountNUMERIC(12,2) |
|---|---|---|---|
| 1 | AC-900 | 2026-01-03 | 48200.00 |
| 2 | AC-901 | 2026-01-07 | 126500.00 |
| 3 | AC-902 | 2026-01-12 | 91000.00 |
| 4 | AC-903 | 2026-01-18 | 126500.00 |
| 5 | AC-904 | 2026-01-24 | 33750.50 |
| 6 | AC-905 | 2026-02-01 | 108900.00 |
| 7 | AC-906 | 2026-02-06 | 15400.00 |
| 8 | AC-907 | 2026-02-11 | 72300.00 |
invoices
- invoice_idINT
- account_codeTEXT
- issued_onDATE
- amountNUMERIC(12,2)
- Step 1: Deduplicate the amounts first — two accounts share the top amount of 126500, and “second highest distinct” must skip that tie.
- Step 2: Sort the distinct amounts descending, then skip one row with `OFFSET 1` and take one row with `LIMIT 1`.
- Step 3: Wrap that query as a **scalar subquery** in the `SELECT` list. A scalar subquery that finds nothing yields `NULL`, which satisfies the “return NULL, not zero rows” requirement.
- Step 4: Alias the result as `second_highest_amount`.
SELECT (
SELECT DISTINCT amount
FROM invoices
ORDER BY amount DESC
OFFSET 1
LIMIT 1
) AS second_highest_amount;Approach 2 — MAX of everything below the MAX
A classic nested aggregate version that avoids `OFFSET` entirely.
SELECT MAX(amount) AS second_highest_amount
FROM invoices
WHERE amount < (SELECT MAX(amount) FROM invoices);Learn the concept first
Stuck on Subqueries? These free SQL lessons teach it step by step.
More Subqueries questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program