Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude some values in sorting with MySQL?

I have a table like this:

id products_name sort
1   abc           0 
2   xyz           1
3   pqr           2
4   qwe           0

I want to sort records through the sort column and in ascending order, but I don't want the rows with 0 at the top in the result set.
The rows having 0 in the sort column should be at the bottom of the result set, and the rest of the rows should be sorted in ascending order using the sort column.

How do I do this?

like image 642
Pradeep Singh Avatar asked Sep 26 '11 07:09

Pradeep Singh


2 Answers

You could try something like:

ORDER BY IF(SORT=0, 999999999, SORT)
like image 63
Romain Avatar answered Nov 19 '22 22:11

Romain


You can use the ORDER BY IF statement:

SELECT *
FROM table
ORDER BY IF(SORT = 0, 999999999, SORT)

or you can use the UNION ALL statement to achieve this:

(SELECT * FROM table WHERE sort > 0 ORDER BY sort)
UNION ALL
(SELECT * FROM table WHERE sort = 0)
like image 22
MC Emperor Avatar answered Nov 19 '22 23:11

MC Emperor