Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort with one option forced to top of list

Tags:

sql

sorting

I have a PHP application that displays a list of options to a user. The list is generated from a simple query against SQL 2000. What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.

For example, here's the options if sorted alphabetically:

Calgary  
Edmonton  
Halifax  
Montreal  
Toronto  

What I would like the list to be is more like this:

**Montreal**  
Calgary  
Edmonton  
Halifax  
Toronto  

Is there a way that I can do this using a single query? Or am I stuck running the query twice and appending the results?

like image 432
Wally Lawless Avatar asked Dec 30 '22 10:12

Wally Lawless


2 Answers

SELECT name
FROM locations
ORDER BY
    CASE
        WHEN name = 'Montreal' 
        THEN 0
        ELSE 1
    END, name
like image 163
Matt Rogish Avatar answered Jan 08 '23 02:01

Matt Rogish


SELECT name FROM options ORDER BY name = "Montreal", name;

Note: This works with MySQL, not SQL 2000 like the OP requested.

like image 27
mercutio Avatar answered Jan 08 '23 02:01

mercutio