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:
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!
(Lifetime Access/ Live Demos / Downloadable Resources and more!)
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;
Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018) and a Udemy Instructor. He has over 15 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and TechHowTos.com. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.
This site uses cookies for personalized content and the best possible experience. By continuing to browse this site, you agree to this use. Find out more.