How do I return rows with a specific value first?

Phoexo picture Phoexo · Aug 9, 2009 · Viewed 82.5k times · Source

I want my query to return the rows of the table where a column contains a specific value first, and then return the rest of the rows alphabetized.

If I have a table something like this example:

 - Table: Users
 - id - name -  city
 - 1    George  Seattle
 - 2    Sam     Miami
 - 3    John    New York
 - 4    Amy     New York
 - 5    Eric    Chicago
 - 6    Nick    New York

And using that table I want to my query to return the rows which contain New York first, and then the rest of the rows alphabetized by city. Is this possible to do using only one query?

Answer

Rob Farley picture Rob Farley · Aug 9, 2009

On SQL Server, Oracle, DB2, and many other database systems, this is what you can use:

ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city