SQL error · The query will not run

DISTINCT fails with an ORDER BY column

Problem: The sort depends on a column that does not define each distinct row in the result.

Solution: Sort by the selected column, or define a rule per group such as MIN(id), without changing what the query means.

Why it happens: DISTINCT fails with an ORDER BY column

Suppose you want a list of cities without duplicates, but you also try to sort them by customer id:

Problem pattern on strict engines
SELECT DISTINCT city
FROM customers
ORDER BY id;

Without DISTINCT, sorting by id is usually valid even if you do not display it. With DISTINCT city, several rows from customers can collapse into a single city. That raises a question the query does not answer: if London belongs to customers 1, 3, 6 and 9, which id should represent the single «London» row when sorting?

“DISTINCT fails with an ORDER BY column” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
MySQLERROR 3065 (HY000): Expression #1 of ORDER BY clause is not in SELECT list, references column 'store.customers.id' which is not in SELECT list; this is incompatible with DISTINCT
SQL ServerMsg 145, Level 15: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
OracleORA-01791: not a SELECTed expression

SQLite accepts that query without an error, but the resulting order is not well defined.

How to fix it in SQL

1. If you only want a sorted list of unique values, sort by the value itself

Unique cities in alphabetical order
SELECT DISTINCT city
FROM customers
ORDER BY city;
Result verified locally in SQLite
city
Edinburgh
Bristol
London
Leeds
Manchester
Birmingham

2. If you want to sort each unique value by a property of its group, define that property

For example, “cities sorted by the first customer recorded in the table” is a specific rule. You can group by city and sort by the lowest id:

Sorting the groups by a defined measure
SELECT city
FROM customers
GROUP BY city
ORDER BY MIN(id), city;
Result verified locally
cityMIN(id), which sets the order
London1
Manchester2
Bristol4
Leeds5
Birmingham10
Edinburgh12

The helper column does not need to appear in the output for the intent to be valid: here MIN(id) is computed unambiguously for each city.

3. If you need to remove duplicates first and sort by a helper key afterwards, split the stages

A subquery or CTE can turn the helper criterion into an explicit column during deduplication and let the outer query decide what to show:

Separate deduplication from presentation
SELECT status
FROM (
  SELECT DISTINCT
         status,
         CASE status
           WHEN 'pending' THEN 1
           WHEN 'shipped' THEN 2
           WHEN 'cancelled' THEN 3
           ELSE 4
         END AS priority
  FROM orders
) AS statuses
ORDER BY priority, status;

In this example, priority depends only on status, so including it in the deduplication creates no new duplicates. The outer query returns only status.

How to check it

Count the cities before and after: adding id to SELECT must not turn each customer into a separate result.

How to avoid it next time

First decide what one result row represents, then decide how to sort it.

Related cases worth checking

Common mistake: adding the column to SELECT can change what DISTINCT means

Fix that only looks right
SELECT DISTINCT city, id
FROM customers
ORDER BY id;

This query no longer asks for unique cities. It asks for unique combinations of city + id. Because id is unique, almost every customer becomes a separate row again. If your goal was to remove duplicate cities, you have changed the question.

Rule of thumb: Only add the sort expression to the SELECT DISTINCT when it is a legitimate part of the identity you want to return, or a deterministic function of that identity that does not affect deduplication.

The rule differs between engines

EngineRelevant behaviourWhat to do
PostgreSQLLets you sort by unselected expressions in a SELECT plain query, but with SELECT DISTINCT it may require the ORDER BY expression to appear in the output list.Make the sort key explicit or split the stages.
MySQL 8.4With ONLY_FULL_GROUP_BY enabled (the default) rejects DISTINCT + ORDER BY combinations that would produce an arbitrary order because the sort expression is not represented in the select list.Do not switch the mode off to hide the ambiguity; rewrite the query.
SQL ServerWith SELECT DISTINCT, the names or aliases used in ORDER BY must be defined in the select list.Include a legitimate key or use an outer query.
SQLiteIn a SELECT plain SQLite allows arbitrary expressions in ORDER BY. The problem query may run locally even though other engines reject it.Do not treat that leniency as a portable guarantee; state the sort rule explicitly.

Important: the fact that SQLite accepts SELECT DISTINCT city ... ORDER BY id does not prove the query is portable or that its intent is well defined. When the order depends on a “representative” row, define how that row is chosen.