Descending order, except

Here's a query with the result:

SELECT id, name FROM medic WHERE x=z ORDER BY name ASC

1. Aric
2. Bodi
3. Copi
4. Dori
5. Edo
6. Other
7. Poyo
8. Quex
9. Razix
10. Zika

      

Which is better if I need to display " Other " at the end as the result below:

1. Aric
2. Bodi
3. Copi
4. Dori
5. Edo
7. Poyo
8. Quex
9. Razix
10. Zika
6. Other

      

+3


source to share


3 answers


In MySQL, you can simply use a boolean expression:

ORDER BY (name <> 'Other') DESC,
         name

      



MySQL treats Boolean expressions as numbers in a numeric context, with "1" for true and "0" for false. (I like this convention and would like other databases to have similar support.) This can be useful in these cases.

+2


source


One option is to order using the expression CASE

:



SELECT
    id,
    name
FROM medic
WHERE x=z
ORDER BY
    CASE WHEN name <> 'Other' THEN 0 ELSE 1 END,
    name

      

+2


source


Either use two expressions in the ORDER BY clause, or we can replace the value we want in the past with a "high" value.

ORDER BY IF(t.name='Other', 'ZZZZZZZ', t.name)

      

0


source







All Articles