I have a problem with order by. We know that if we give integer in order by then it orders via index of column. When I use it this way every time I execute query, I get same result, which is correct.
But when I make this value the result of an expression (I mean I use a expression which always evaluates to 1), then I get 3 possible combinations of result when I execute it.
So for same value which is static, same result; but for same value which is an evaluated expression, different results.
Below is the example of query which I am referring to:
SELECT SomeColumns, (rand()* 10) as rand
FROM TableName
ORDER BY (if ((rand in (1) ), 1,1))
LIMIT 0 , 6
The above query gives three possible result sets.
ORDER BY‘s syntax is:Although the following would appear to the human-eye to be equivalent:
they are not.
The first one sorts by the
1st column’s data, as it’s an integer with value1.The second one, although it evaluates to
1, is not an integer but an expression and, as such, a different sorting mechanism is invoked. For each row, the expression1is evaluated and used to determine the row’s position; because your expression actually doesn’t refer to row data at all, your results will be completely unpredictable.Whether you’ll get the table’s “natural order” (that is, the physical ordering that happens to be present underneath the relational abstractions) or some random-looking order that the
ORDER BYcreated I couldn’t say, but it also doesn’t matter.Usually you’d write something like this for an expression:
… i.e. something that references data.