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

When writing T-SQL code, at some point, under certain circumstances, you might get the error message: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

 

Explaining the Error Message with an Example

But let’s take things from  the beginning with the use of an example.

First, let’s create a temporary table:

CREATE TABLE #tmpTable
    (
        id INT PRIMARY KEY ,
        code VARCHAR(50) ,
        age INT
    );

Then, let’s populate the table with some sample data:

INSERT INTO #tmpTable
VALUES ( 1, 'code 1', 25 ) ,
       ( 2, 'code 2', 27 ) ,
       ( 3, 'code 3', 29 ) ,
       ( 4, 'code 4', 25 ) ,
       ( 5, 'code 5', 21 ),
       ( 6, 'code 5', 21 );

 

Reproducing the Error Message

Now let’s run the below query, which tries to retrieve the distinct “age” values along with sorting the results based on the id:

SELECT   DISTINCT age
FROM     #tmpTable
ORDER BY code;

However, when we execute the above query, we get the error message:

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

 


Strengthen your SQL Server Administration Skills – Enroll to our Online Course!

Check our online course on Udemy titled “Essential SQL Server Administration Tips
(special limited-time discount included in link).

Via the course, you will learn essential hands-on SQL Server Administration tips on SQL Server maintenance, security, performance, integration, error handling and more. Many live demonstrations and downloadable resources included!

Essential SQL Server Administration Tips - Online Course with Live Demonstrations and Hands-on Guides
(Lifetime Access/ Live Demos / Downloadable Resources and more!)

Learn More


Resolving the Issue

As the error message indicates, you are using in the ORDER BY clause, a column which is not included in the SELECT list. In this case this column is “code”.

Therefore, you definitely need to include in your query the column “code”.

So, for this example, you can try running the query as below:

SELECT   DISTINCT age,code
FROM     #tmpTable
ORDER BY code;

 

Featured Online Courses:

 

Other SQL Server troubleshooting articles to check on SQLNetHub:

 

Subscribe to the GnoelixiAI Hub newsletter on LinkedIn and stay up to date with the latest AI news and trends.

Subscribe to the SQLNetHub YouTube channel (SQLNetHub TV).

Subscribe to my personal YouTube channel.

 

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 5.00 out of 5)

Loading...

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub