lyen lyen - 7 months ago 9
SQL Question

Why is this MySQL query correct?

I have a table which has only 3 columns. When I type the following query

select * from MyTable order by 5 and 2;


I get every thing in the table( The result is equal to that of
select * from MyTable;
). What I originally expected is that I would get some kind of error. But I didn't get it, why?

Answer

What is happenning here is that 5 and 2 is seen as an expression which is evaluated to 1. However, it shouldn't give a result sorted by first column.

Actually, I think you only get sorted data because you inserted it in sorted sequence. Take a look at this SQLFiddle:

http://sqlfiddle.com/#!2/3e04e/1

The data is not sorted by any of the columns, it is being sorted by a value 1.