Andrew
Andrew

Reputation: 239187

MySQL order by multiple case statements

I have a situation where I need to sort my records by their "status" which is made up of a combination of fields. Here is an example how it should return the results sorted by status in ascending order:

        |     Sent      Received         Approved
--------------------------------------------------
record1 |     null        null             null
record2 |  2012-01-01     null             null
record3 |  2012-01-01   2012-01-01         null
record4 |  2012-01-01   2012-01-01      2012-01-01

How would I create a MySQL query that would order these records by their overall "status"?

Upvotes: 7

Views: 14480

Answers (1)

DRapp
DRapp

Reputation: 48179

order by
   case when sent is null and received is null and approved is null then 1
        when received is null and approved is null then 2
        when approved is null then 3
        else 4 end

Upvotes: 12

Related Questions