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.




Related Articles :

  • No Related Articles Found

No comments yet... Be the first to leave a reply!

Software Reviews | Book Reviews | FAQs | Tips | Articles | Performance Tuning | Audit | BI | Clustering | Developer | Reporting | DBA | ASP.NET Ado | Views tips | | Developer FAQs | Replication Tips | OS Tips | Misc Tips | Index Tuning Tips | Hints Tips | High Availability Tips | Hardware Tips | ETL Tips | Components Tips | Configuration Tips | App Dev Tips | OLAP Tips | Admin Tips | Software Reviews | Error | Clustering FAQs | Performance Tuning FAQs | DBA FAQs |