// SQL snippet

Second-highest value

MAX of everything below the MAX for one value, DENSE_RANK when you need it per group.

Main statement
All engines

The task

You want the second-highest order amount. MAX(amount) gives the highest, and the naive ORDER BY amount DESC LIMIT 1 OFFSET 1 returns the top amount again when two orders share it.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT MAX(amount) AS second_highest
FROM orders
WHERE amount < (SELECT MAX(amount) FROM orders);

Como funciona

The inner query finds the highest amount; the outer query takes the MAX of everything strictly below it. Duplicate rows at the top collapse into one MAX, so two orders tied at the highest still yield the true second value. If only one distinct amount exists the result is NULL rather than an error.

Variations

Second-highest per customer with DENSE_RANK

WITH ranked AS (
  SELECT customer_id, amount,
         DENSE_RANK() OVER (PARTITION BY customer_id
                            ORDER BY amount DESC) AS rnk
  FROM orders
)
SELECT customer_id, amount
FROM ranked
WHERE rnk = 2
ORDER BY customer_id;

DISTINCT + LIMIT/OFFSET (PostgreSQL, MySQL, SQLite)

PostgreSQL MySQL SQLite
SELECT DISTINCT amount
FROM orders
ORDER BY amount DESC
LIMIT 1 OFFSET 1;

Questions that come up

Why DENSE_RANK and not ROW_NUMBER for the per-customer version?

ROW_NUMBER counts rows, so two orders tied at the highest amount would make the second row the 'second highest'. DENSE_RANK counts distinct values, which is usually what people mean by second-highest.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.