Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by multiple case statements

Tags:

mysql

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"?

like image 838
Andrew Avatar asked Feb 27 '12 17:02

Andrew


People also ask

Can I use ORDER BY in case statement?

Although it is most often used there, CASE is not limited to SELECT statements. For example, you can use it in clauses like IN , WHERE , HAVING , and ORDER BY . Using a CASE statement in a query once doesn't mean you have hit your quota for using it. You can use it multiple times in a single query.

Can we use 2 ORDER BY in MySQL?

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.

Can you ORDER BY a case statement in SQL?

SQL order by case can be used when we have to order the data on a conditional basis and define the criteria on which the ordering will be done based on a certain condition.

How do you use case in order?

CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.


1 Answers

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
like image 116
DRapp Avatar answered Sep 25 '22 14:09

DRapp