The following code:
SELECT JaguarStartupTime, CPU, AmountOfRam, UpdatedOn, *
FROM dbo.MachineConfiguration
WHERE ServerName = 'WashingtonDC01'
AND UpdatedOn > '11/21/2012'
ORDER BY JaguarStartupTime DESC
results in an error: Ambiguous column name 'JaguarStartupTime'.
However, removing the ORDER BY makes it work. In addition, prefixing the ORDER BY clause with the table, like below, makes it work too:
SELECT JaguarStartupTime, CPU, AmountOfRam, UpdatedOn, *
FROM dbo.MachineConfiguration
WHERE ServerName = 'WashingtonDC01'
AND UpdatedOn > '11/21/2012'
ORDER BY dbo.MachineConfiguration.JaguarStartupTime DESC
This never made sense to me. Can someone explain?
Because the query includes
*(all columns) in the SELECT clause, which also includes the column JaguarStartupTime.In Layman’s terms:
So in the retrieval of the results, the column shows up twice, and then when the server tries to apply the sort order, it’s not sure which column you are referring to.
Personally, I’d change the query to eliminate the use of
*in the query, even if it means listing a long list of column names. It’s best practice, and it will avoid this issue.As for why it works when prefixed, I found this in the MSDN documentation:
This is simply part of the DB engine’s underlying mechanism for translating SQL statements into the execution plan.