Home › Databases

ERROR 3065 (HY000): Expression #1 of ORDER BY clause is not in SELECT list ... this is incompatible with DISTINCT (MySQL) — how to fix

ERROR 3065 (HY000): Expression #1 of ORDER BY clause is not in SELECT list, references column 'shop.orders.created_at' which is not in SELECT list; this is incompatible with DISTINCT

Quick fix: Add the ORDER BY column to the SELECT list, or replace DISTINCT with GROUP BY and order by an aggregate: SELECT customer_id FROM orders GROUP BY customer_id ORDER BY MAX(created_at) DESC;

What it means

SELECT DISTINCT customer_id
FROM orders
ORDER BY created_at DESC;      -- ERROR 3065

DISTINCT collapses many orders into one row per customer_id. Each collapsed row has many different created_at values, so "sort by created_at" is ambiguous. MySQL 5.7.5 and later reject it with the default SQL mode. PostgreSQL rejects the same query with "for SELECT DISTINCT, ORDER BY expressions must appear in select list".

Decide what you actually want to sort by, then use one of the fixes below.

Fix 1: select the ORDER BY column too

If including it is fine (it doesn't break the uniqueness you want):

SELECT DISTINCT customer_id, created_at
FROM orders
ORDER BY created_at DESC;

Be aware this returns one row per (customer_id, created_at) pair, so customers can appear several times.

Fix 2: GROUP BY with an aggregate (usual answer)

"Distinct customers, most recent first":

SELECT customer_id, MAX(created_at) AS last_order
FROM orders
GROUP BY customer_id
ORDER BY last_order DESC;

You don't have to return the aggregate:

SELECT customer_id
FROM orders
GROUP BY customer_id
ORDER BY MAX(created_at) DESC;

Use MIN() for "first seen" order, COUNT(*) for "most orders" and so on.

Fix 3: sort by an expression that is selected

If the ORDER BY column is a function of selected columns, write the same expression in both places, or order by the alias:

SELECT DISTINCT LOWER(email) AS email_lc
FROM users
ORDER BY email_lc;

Fix 4: ORMs and query builders

Frameworks often add DISTINCT automatically (for joins or pagination) while keeping your ORDER BY. Typical cases:

Enable the general query log or print the generated SQL to see the real query.

Don't disable the SQL mode as a fix

Changing sql_mode (for example removing ONLY_FULL_GROUP_BY) is often suggested for GROUP BY errors, but even where a looser mode lets a query like this run, MySQL picks an arbitrary row's value to sort by, so the order can be wrong or change between runs. Rewrite the query instead. The related GROUP BY error is explained in ERROR 1055 only_full_group_by.

For checking long generated queries, paste them into the SQL formatter.

Last updated 2026-12-05.