ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

Error Message:
Msg 104, Level 16, State 1, Line 1
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

Severity level:
16.

Description:
This error message appears when you try to sort a resultset by an element that is not contained in the SELECT list and the statement contains a UNION-, INTERSECT-, or EXCEPT operator.

Consequences:
The SQL statement can be parsed, but cannot be executed and execution is stopped.

Resolution:
Error of the Severity Level 16 are generated by the user and can be fixed by the SQL Server user. Either you need to modify the ORDER BY clause so that only it includes only elements that also appear in the SELECT list, or remove the ORDER BY clause, or add that particular expression to the SELECT list.

Versions:
All versions of SQL Server.

Example(s):
SELECT OrderID, EmployeeID
  FROM Northwind.dbo.Orders
 WHERE CustomerID = ‘ALFKI’
UNION ALL
SELECT OrderID, EmployeeID
  FROM Northwind.dbo.Orders
 WHERE CustomerID != ‘ALFKI’
 ORDER BY OrderDate

Remarks:
In the above example we try to sort by the OrderDate column. Because this column is not contained in the SELECT list and the query contains one of the above mentioned operators, the error is raised.

]]>

Leave a comment

Your email address will not be published.