91

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,374
  • 4
  • 30
  • 44

4 Answers4

189

Try this:

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

should work (for mySql)

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
33
SELECT *
FROM TableX
ORDER BY (requestId IS NOT NULL)
       , requestId DESC
mb21
  • 34,845
  • 8
  • 116
  • 142
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
0

A shorter way: SELECT * FROM table ORDER BY -column

This will sort rows ascending order but the values negated, where top rows are rows with null value.

MobCode100
  • 166
  • 1
  • 5
0

I know the op is tagged with mysql, but if anyone got here looking for a solution for SQLServer, where is seems is null is not supported in the order by clause, use the following:

ORDER BY iif(requestId IS NULL,1,0)
       , requestId DESC
GilShalit
  • 6,175
  • 9
  • 47
  • 68