Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Orderby a number, Empty Strings (or 0's) Last

Just asked a question pretty similar to this one...

Currently I am doing a very basic OrderBy in my statement.

SELECT * FROM tablename WHERE visible=1 ORDER BY position ASC, id DESC

The problem with this is that empty string entries for 'position' are treated as 0. Therefore all entries with position as empty string appear before those with 1,2,3,4. eg:

'', '', '', 1, 2, 3, 4

or:

0, 0, 0, 1, 2, 3, 4

Is there a way to achieve the following ordering:

1, 2, 3, 4, '', '', ''.

or:

1, 2, 3, 4, 0, 0, 0.

I assume the solution may have some kind of replace function but I am not able to find a function which does what I am after.

like image 315
JonB Avatar asked Jan 12 '10 20:01

JonB


1 Answers

SELECT * 
FROM tablename 
WHERE visible=1 
ORDER BY 
    case when position in('', '0') then 1 else 0 end,
    position ASC, 
    id DESC
like image 127
D'Arcy Rittich Avatar answered Sep 19 '22 06:09

D'Arcy Rittich