1

I have multiple rows in a table and they have columns status and edited. Value of status can be 0, 1, 2 or 3. Following is my query.

SELECT * FROM orders ORDER BY FIELD(status, 1, 0, 2, 3), edited ASC

Is it possible to order results also based on the value of status like that:

if status = '0' => edited DESC
if status = '1' => edited DESC
if status = '2' => edited ASC
if status = '3' => edited ASC

Can I do this in one query or do I need to do separated queries?
Thanks in advance.

4
  • Did you mean if status = '0' => edited DESC and so on ? Commented Sep 3, 2015 at 12:58
  • @Abhik, yes. Thanks for question, I edited my post. Commented Sep 3, 2015 at 12:59
  • 3
    Not sure about the data but this might be helpful for you sqlfiddle.com/#!9/7e8bc/2 Commented Sep 3, 2015 at 13:06
  • 1
    @Abhik, thanks very much. That works! Commented Sep 3, 2015 at 13:10

2 Answers 2

2

You should use Order By Case query

Syntax

 order By   
    CASE 
           WHEN status =0 THEN 0 
             ...

        END DESC 
Sign up to request clarification or add additional context in comments.

Comments

0

Check this query too to get your sorted output:

SELECT * FROM test ORDER BY FIELD(status, 0, 1)DESC, FIELD(status, 2, 3)ASC, edited ASC

Reference for the script

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.