I agree that in the case in your question ORDER BY JaguarStartupTime
is not really ambiguous as both projected columns in fact refer to the same underlying column.
In the general case however there is no guarantee that this will be true. As discussed in the response to this connect item. For example in the following query it is clearly ambiguous which one would be used.
SELECT JaguarStartupTime,
CPU AS JaguarStartupTime
FROM dbo.MachineConfiguration
ORDER BY JaguarStartupTime DESC
For syntax validation purposes SQL Server does not do any analysis of column names to determine whether they are really ambiguous or not. When ordering by some_name
that is present in the list of projected column names the some_name
must be unique. This is as per the ANSI spec
If a <sort specification>
contains a <column name>
, then T
shall contain exactly one column with that <column name>
and
the <sort specification>
identifies that column.
Qualifying the column name with the table name ensures to SQL Server that you are ordering by a source column name rather than a projected column name so it allows it.
SELECT name, name
FROM master..spt_values v1
ORDER BY v1.name
Additionally the following query is allowed.
select name, name
FROM master..spt_values v1
ORDER BY name + ''
The reason why this is not ambiguous is because column aliases in an ORDER BY
clause can only be used by themselves rather than in an expression so in the above query name
can not be interpreted as an alias and must be interpreted as ordering by v1.name
.