Column "%1!.%2!" is invalid in the ORDER BY clause

Error Message:
Msg 8127, Level 16, State 1, Line 1
Column “%1!.%2!” is invalid in the ORDER BY clause

Severity level:
16.

Description:
This error message appears when you try to run an SQL statement, in which you try to sort by a column, that is neither contained in an aggregate function nor in the GROUP BY clause.

Consequences:
The T-SQL statement can be parsed, but causes the error at runtime.

Resolution:
Error of the severity level 16 are generated by the user and can be fixed by the SQL Server user. The SQL statement needs to be corrected.

Versions:
All versions of SQL Server.

Example(s):
USE Northwind
GO
SELECT CustomerID, COUNT(*)
  FROM dbo.Orders
 GROUP BY CustomerID
 ORDER BY OrderDate

Remarks:
In the above example the error is raised because the final resultset should be sorted by the OrderDate column. This column, however, is not referenced in the GROUP BY clause, nor is an aggregate function applied on it. You can eliminate this error either by referencing OrderDate also in the GROUP BY clause like:

SELECT CustomerID, COUNT(*)
  FROM dbo.Orders
 GROUP BY CustomerID, OrderDate
 ORDER BY OrderDate

or by applying an aggregate function on OrderDate like:

SELECT CustomerID, COUNT(*)
  FROM dbo.Orders
 GROUP BY CustomerID
 ORDER BY MAX(OrderDate)

Now the statements are syntactically correct, but you have to carefully check if the result is still what you expect.

]]>

Leave a comment

Your email address will not be published.