136

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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Phoexo
  • 2,485
  • 4
  • 25
  • 33
  • Consider changing the accepted answer to the second one if you can, as the first one only works for MySQL and not for MSSQL. – Magisch Mar 06 '17 at 08:23
  • Done. My original question was about MySQL, but the tags did not reflect that anyway. – Phoexo Mar 06 '17 at 15:25
  • Thank you. I came across this this morning in an effort to do something similar for a problem I had. :) – Magisch Mar 06 '17 at 16:29

3 Answers3

215

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
Rob Farley
  • 15,625
  • 5
  • 44
  • 58
107

If your SQL dialect is intelligent enough to treat boolean expressions as having a numeric value, then you can use:

SELECT *
FROM `Users`
ORDER BY (`city` = 'New York') DESC, `city`
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 1
    @MehrdadAfshari: No, MSSQL is too stupid to process equivalency tests in the `ORDER BY` clause. – chaos Sep 11 '13 at 15:13
  • @a_horse_with_no_name: Have you tried running the above query against MSSQL? – chaos Sep 25 '13 at 15:01
  • 11
    @chaos: the above statement does indeed *not* run with SQL Server, but that's because the syntax is non-standard and only works for MySQL. When using a `CASE` statement (which is standard SQL) SQL Server can very well use an expression in the `ORDER BY` clause. "*too stupid to process equivalency tests*" is simply wrong. If at all it should read: "*does not support MySQL's implicit casting of boolean `true` to the value `1` (one).*" –  Sep 25 '13 at 15:02
  • @Esraa_92: Then you don't have a SQL dialect that can handle it and you need Rob Farley's answer. – chaos May 13 '16 at 19:08
  • 6
    For Postgres, this worked for me: `ORDER BY id = 123 DESC, name ASC` – user1032752 Oct 06 '16 at 21:27
6

My answer may be old and not required but someone may need different approach,hence posting it here.

I had same requirement implemented this, worked for me.

Select * from Users
ORDER BY
(CASE WHEN city = 'New York' THEN 0 ELSE 1 END), city
GO

PS

this is for SQL

Manjuboyz
  • 6,978
  • 3
  • 21
  • 43