D
D
Denis Ogurtsov2014-12-28 15:52:27
MySQL
Denis Ogurtsov, 2014-12-28 15:52:27

Difference between ORDER by 1 and ORDER by IF(somefield='foobar', 1,0)?

What's the Difference

SELECT name, name2 FROM table 
ORDER by  1

from
SELECT name, name2 FROM table 
ORDER by  IF(name='denis', 1,0)

The first example sorts by the first list from the select, and the second one fails to sort if name=denis and puts the string at the beginning (this is the case in the documentation and in the examples) But why? If passes IF that will be 1?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2014-12-28
@DenisOgr

select fieldname /*, ... */ from tablename order by 1

This is an abbreviated version
The number indicates the ordinal number of the field in this select. The syntax, as they themselves noticed, is not obvious, so it's better not to use it.
ORDER by IF(name='denis', 1,0) , like any other expression, is a condition evaluation or expression and sorting by the result of this expression.
Equivalent
select IF(name='denis', 1,0) as sortfield, /*fields*/ from tablename order by sortfield

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question