| title | Column aliases in ORDER BY clause cannot be prefixed by table alias | Microsoft Docs | |
|---|---|---|
| ms.custom | ||
| ms.date | 03/06/2017 | |
| ms.prod | sql-server-2014 | |
| ms.reviewer | ||
| ms.technology | database-engine | |
| ms.topic | conceptual | |
| helpviewer_keywords |
|
|
| ms.assetid | fee7328f-6e8d-4005-930b-56fb6f17e0b2 | |
| author | mashamsft | |
| ms.author | mathoma | |
| manager | craigg |
In [!INCLUDEssVersion2005] or later, column aliases in the ORDER BY clause cannot be prefixed by the table alias.
[!INCLUDEssDE]
For example, the following query executes in [!INCLUDEssVersion2000], but returns an error in [!INCLUDEssKatmai]:
USE AdventureWorks2012;
GO
SELECT FirstName AS f, LastName AS l
FROM Person.Contact p
ORDER BY p.l
The [!INCLUDEssDEversion10] does not match p.l in the ORDER BY clause to a valid column in the table.
If the prefixed column alias that is specified in the ORDER BY clause is a valid column name in the specified table, the query executes without error; in [!INCLUDEssCurrent], the semantics of the statement might be different. For example, the column alias (id) specified in the following statement is a valid column name in the sysobjects table. In [!INCLUDEssVersion2000], when the statement executes, the CAST operation is performed after the result set is sorted. This means the name column is used in the sort operation. In [!INCLUDEssKatmai], the CAST operation occurs before the sort operation. This means the id column in the table is used in the sort operation and returns the result set in an unexpected order.
SELECT CAST (o.name AS char(128)) AS id
FROM sysobjects AS o
ORDER BY o.id;
Modify queries that use column aliases prefixed by table aliases in the ORDER BY clause in either of the following ways:
-
Do not prefix the column alias in the ORDER BY clause, if possible.
-
Replace the column alias with the column name.
For example, both of the following queries execute without error in [!INCLUDEssKatmai]:
USE AdventureWorks2012;
GO
SELECT FirstName AS f, LastName AS l
FROM Person.Contact p
ORDER BY l
USE AdventureWorks2012;
GO
SELECT FirstName AS f, LastName AS l
FROM Person.Contact p
ORDER BY p.LastName
Database Engine Upgrade Issues
SQL Server 2014 Upgrade Advisor [new]