Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

14 January 2008

MySQL: Sort ascending with blanks at end

It makes sense to have blanks at the start of an A-Z query, as a shorter length string should always appear before a longer length string starting with the same letters. However, sometimes it's convenient to clump any completely black records at the end.

I couldn't think of a perfect way of doing this, but here's a fairly nice solution...

ORDER BY IF(LENGTH(name)>0, CONCAT('1',name), '2') ASC

The IF() function is used to prepend a '1' to any non-zero length string, and '2' to any zero length string. For the latter, we already know that the string is empty so there's no need to use CONCAT().