ORDER BY with DISTINCT SQL Origin: Data OSI layer 7 · Application Last updated 18 Nov 2026

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

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

Exact message you may see ORDER BY items must appear in the select list if SELECT DISTINCT is specifiedfor SELECT DISTINCT, ORDER BY expressions must appear in select listORDER BY clause is not in SELECT list, references column which is not in SELECT listDISTINCT ORDER BY error
Seen on: SQL PostgreSQL SQL Server

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?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

Where this error sits

Origin: Data. Errors that are often confused with or caused by this one (click to open):

1248 — MySQL ERROR 1248 (42000): Every derived table must have its own alias (SQL)12488120 — SQL Server Msg 8120: Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause (SQL)8120cartesian — Query returns far too many rows: accidental Cartesian product (missing JOIN condition) (SQL)cartesianCASE — CASE expression returns mixed types: conversion failed / types cannot be matched (SQL)CASECOUNT — COUNT(column) ignores NULLs: counts differ from COUNT(*) (SQL)COUNTGROUP BY — Column must appear in the GROUP BY clause / isn't in GROUP BY (MySQL 1055 only_full_group_by) (SQL)GROUP BYLIMIT — LIMIT/TOP without ORDER BY returns different rows each time (SQL)LIMITORDER BY …

Explore the map of this error Full error map →

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.

💬 What worked for others

No tips yet — did something else fix this for you?

Share what worked for you

Tips are checked by an editor before they appear. Links are removed.