Chris Tate-Davies

An archive of helpful tit bits of information for development, and probably some stuff that is incomplete, wrong or boring…

MySQL – Order by certain value first

Posted on | March 23, 2010 | 1 Comment

Ever wanted to sort a resultset of data, by value, but I wanted a couple of exceptions to appear at the top?

SELECT country, population,
CASE country
WHEN 'United Kingdom' THEN 0
WHEN 'United States' THEN 1
WHEN 'New Zealand" THEN 2
ELSE country
END AS countrySort
FROM countryList 
ORDER BY countrySort ASC;

This will sort the results by country, but with UK, US, NZ as the top three.

 

Comments

One Response to “MySQL – Order by certain value first”

  1. Jenrik
    March 29th, 2010 @ 6:19 pm

    Thankyou, I looked everywhere for this and it is so easy.

Leave a Reply