# How to find the second highest (or Nth) value in SQL

Source: https://sqlstreak.com/sql/how-to/nth-highest-value · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** Rank the values with `DENSE_RANK() OVER (ORDER BY value DESC)` and keep rank N: ties share a rank and no number is skipped. For the second highest only, `MAX(value)` below the overall `MAX` also works. `LIMIT 1 OFFSET N-1` is only right on distinct values.

**The task:** Find the second highest value in a column, or more generally the Nth.

### DENSE_RANK: the second heaviest weight

```sql
SELECT DISTINCT weight_kg
FROM (SELECT weight_kg,
        DENSE_RANK() OVER (ORDER BY weight_kg DESC) AS r
      FROM pets) ranked
WHERE r = 2;
```

Result (both engines):

| weight_kg |
| --- |
| 27.3 |

### MAX below the MAX

Fine for second place; it gets awkward for third and beyond.

```sql
SELECT MAX(weight_kg) AS second_heaviest
FROM pets
WHERE weight_kg < (SELECT MAX(weight_kg) FROM pets);
```

Result (both engines):

| second_heaviest |
| --- |
| 27.3 |

### The OFFSET trap: ties

The second-youngest age should be 2, but three pets are 1 year old, so skipping one row lands on another 1.

```sql
SELECT age AS second_youngest_age
FROM pets
ORDER BY age
LIMIT 1 OFFSET 1;
```

Result (both engines):

| second_youngest_age |
| --- |
| 1 |

### OFFSET on distinct values works

```sql
SELECT DISTINCT age AS second_youngest_age
FROM pets
ORDER BY age
LIMIT 1 OFFSET 1;
```

Result (both engines):

| second_youngest_age |
| --- |
| 2 |

## How it works

- `DENSE_RANK() OVER (ORDER BY weight_kg DESC)`: Numbers the weights from the heaviest: 1, 2, 3…, equal weights sharing a number, with no gaps.
- `FROM (…) ranked`: Window functions can't go in WHERE, so the ranking happens in a subquery first.
- `WHERE r = 2`: Keep second place.
- `SELECT DISTINCT`: If several pets share that weight, show it once.

## Variations

### The Nth value per group

Add PARTITION BY: the second heaviest pet of each species (species with a single pet have no second).

```sql
SELECT species, name, weight_kg
FROM (SELECT species, name, weight_kg,
        DENSE_RANK() OVER (PARTITION BY species ORDER BY weight_kg DESC) AS r
      FROM pets) ranked
WHERE r = 2
ORDER BY species;
```

Result (both engines):

| species | name | weight_kg |
| --- | --- | --- |
| cat | Pumpkin | 5.2 |
| dog | Maple | 27.3 |
| rabbit | Clover | 2.1 |

### When there is no Nth value

The query returns no rows. Wrap it, `SELECT (subquery) AS second`, to get one row with NULL instead.

## Common mistakes

- `RANK` instead of `DENSE_RANK`: after a tie at 1, there is no rank 2.
- `LIMIT 1 OFFSET 1` on values with ties: it returns the second row, not the second value.
- Forgetting DESC: you get the second lowest instead.

## PostgreSQL and SQLite

Same in both engines.
