89

How can I order DESC by a field, but list the NULL values first?

So I'm having a table:

reuestId | offerId | offerTitle
1        | 1       | Alfa
NULL     | 2       | Beta
2        | 3       | Gamma

I want to select them so that the results would be:

NULL | 2 | Beta
2    | 3 | Gamma
1    | 1 | Alfa
Ervin
  • 2,334
  • 3
  • 30
  • 44

2 Answers2

181

Try this:

ORDER BY [reuestId] IS NULL DESC, [reuestId] DESC

should work (for mySql)

DonCallisto
  • 28,203
  • 8
  • 66
  • 94
33
SELECT *
FROM TableX
ORDER BY (requestId IS NOT NULL)
       , requestId DESC
mb21
  • 31,690
  • 8
  • 105
  • 126
ypercubeᵀᴹ
  • 109,746
  • 18
  • 170
  • 231