MySQL ordering alphabetically with empty strings last

Here is a small #MySQL tip: Say you want to order your query results alphabetically, but keep the empty fields last, what do you do? If you do
SELECT string FROM table ORDER BY string;
You will get ‘ ‘, ‘ ‘, ’1′, ’2′, ’3′, ‘A’, ‘B’, ‘C’

But if you do
SELECT string FROM table ORDER BY ! ASCII(string), string;
You will get ’1′, ’2′, ’3′, ‘A’, ‘B’, ‘C’, ‘ ‘, ‘ ‘.

Tip found at www.wonkabar.org

Google+: View post on Google+

Tags: