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!
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:
- SQL Server Security Best Practices
- AI Demystified: A 1-Hour Beginner’s Guide (Suitable for Non-Technical People)
- AI Essentials: A Beginner’s Guide to Artificial Intelligence
- Human-AI Synergy: Teams and Collaborative Intelligence
- Data Management for Beginners – Main Principles
- SQL Server 2022: What’s New – New and Enhanced Features
- Working with Python on Windows and SQL Server Databases
- Introduction to Azure Database for MySQL
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- A Guide on How to Start and Monetize a Successful Blog
Other SQL Server troubleshooting articles to check on SQLNetHub:
- Error converting data type varchar to float
- Operating System Error 170 (Requested Resource is in use)
- There is no SQL Server Failover Cluster Available to Join
- Installing SQL Server 2016 on Windows Server 2012 R2: Rule KB2919355 failed
- Setup failed to start on the remote machine. Check the Task scheduler event log on the remote machine.
- A connection was successfully established with the server, but then an error occurred during the login process.
- SQL Server 2008 R2 Service Pack Installation Fails – Element not found. (Exception from HRESULT: 0x80070490)
- There is insufficient system memory in resource pool ‘internal’ to run this query.
- Argument data type ntext is invalid for argument …
- Could not load file or assembly ‘Microsoft.SqlServer.Smo, Version=10.0.0.0, …
- The operation failed because either the specified cluster node is not the owner of the group, or the node is not a possible owner of the group
- Resolve SQL Server CTE Error – Incorrect syntax near ‘)’.
- … more
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:
Reference: SQLNetHub.com (https://www.sqlnethub.com)
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.