Brian
Brian

Reputation: 13571

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?

Upvotes: 6

Views: 120

Answers (4)

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

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.

Upvotes: 6

Przemyslaw Kruglej
Przemyslaw Kruglej

Reputation: 8123

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.

Upvotes: 2

innovative kundan
innovative kundan

Reputation: 631

select * from MyTable order by 5,2; 
It means start with index 5 and bring 2record i.e 5,6,7

Upvotes: 0

mehmet mecek
mehmet mecek

Reputation: 2685

5 and 2 are column indexes and they mean 5th column and 2nd column.

Upvotes: 1

Related Questions