DISTINCT and ORDER BY together

When we are using DISTINCT we can’t use ORDER BY as we want. If you are going to use DISTINCT when you have ORDER BY, all ORDER BY attributes should be in the SELECT phrase.
USE AdventureWorks2012;
-- Works fineSELECT BusinessEntityIDFROM HumanResources.EmployeeORDER BY BirthDate;
-- FailsSELECT DISTINCTBusinessEntityIDFROM HumanResources.EmployeeORDER BY BirthDate;
-- If you are going to sort with distinct
 result should consist attribute that you are sortingSELECT DISTINCT BusinessEntityIDFROM HumanResources.EmployeeORDER BY BusinessEntityID;

Otherwise, it fails with the following error.
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

Tags

  • SQL
  • SQL Server 2012
  • TSQL
  • SQL Server
  • SQL Sever