# ORDER BY items must appear in the select list if SELECT DISTINCT is specified

**Code:** `ORDER BY with DISTINCT` · **Category:** SQL · **Seen on:** SQL, PostgreSQL, SQL Server

With DISTINCT, the database can only sort by columns that are part of the selected result.

## Meaning

DISTINCT collapses rows, so ordering by a column that isn't selected is ambiguous. Add the column to the select list, use GROUP BY with an aggregate (`MAX(col)`), or wrap the DISTINCT query in a subquery and sort outside.

## Common causes

- ORDER BY column not in the DISTINCT select list
- Expression in ORDER BY not in SELECT
- Joined table column used for sorting
- ORM adding DISTINCT automatically
- Mixed alias and column names

## Quick fix

1. Add the ORDER BY column to the SELECT list
2. Use `GROUP BY` with `MIN/MAX` for sorting
3. Sort in an outer query

## Detailed fix by platform

### SQL

1. 

```sql
SELECT DISTINCT name FROM t ORDER BY name;
SELECT name, MAX(created_at) AS last_seen FROM t GROUP BY name ORDER BY last_seen DESC;
```


## How to diagnose

1. **DISTINCT** — Used?
2. **Sort column** — In SELECT?
3. **ORM** — Adds DISTINCT?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/sql/order-by-items-must-appear-in-select-list-distinct)
