Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this MySQL query correct?

Tags:

mysql

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?

like image 526
Brian Avatar asked Nov 04 '13 13:11

Brian


2 Answers

order by 5 and 2 is interpreted as order by (5 and 2) which is a constant expression, hence no real ordering is done and data is simply shown in the order it was inserted.

like image 131
Matteo Tassinari Avatar answered Sep 22 '22 10:09

Matteo Tassinari


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.

like image 29
Przemyslaw Kruglej Avatar answered Sep 19 '22 10:09

Przemyslaw Kruglej