Skip to content
Advertisement

ORDER BY Has Error on Run Query With Case When

I have this query:

And my tables are like this:

table1

table2

When I run this query, I get this error:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

What’s wrong whit this code?

If I remove Else it works fine

Advertisement

Answer

A case expression returns a single value, with a single type. You are mixing types and hence getting an error. The rules of SQL says that strings are converted to numbers in this situation — and that is where the error is happening.

The simple solution is two expressions:

1 = 1 is rather arcane. This would normally be something like:

You could get rid of the error with an explicit conversion:

However, this would not sort the data numerically for the second case.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement