2

Users Table:

ID|Name|Deleted
1 |    |  N 
2 | b  |  Y 
3 | c  |  N
4 | d  |  N 

Deleted default value is 'N'

I want to order by id desc but I want to display deleted user last.

i.e. when Deleted 'Y' should appear last

2 Answers 2

5

You can use multiple keys in order by. So:

order by (deleted = 'Y') asc, id desc

The expression (deleted = 'Y') is a boolean expression that MySQL treats as a number with 1 for true and 0 for false. The asc puts the true values last.

In most other databases, you would do this with a case:

order by (case when deleted = 'Y' then 1 else 2 end) desc, id desc
Sign up to request clarification or add additional context in comments.

4 Comments

would it be possible to also just do ORDER BY deleted, id DESC (or ORDER BY deleted ASC, id DESC) since the values N/Y are alphabetic order?
@Sean . . . Yes, that is also possible. I tend to be cautious, just in case there could be other values.
THANKS a lot people.
The (deleted = 'Y') version also works well any ANSI SQL compliant dbms that supports boolean. If deleted = 'Y', then TRUE is returned, else FALSE. And FALSE is ordered before TRUE.
0

This will be the simple solution

select * from table_name ORDER BY deleted ASC, id DESC

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.