Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to order a specific value to be last and the rest of the records order by id DESC?

id document_number document_status
1 12335 INFORMED
2 4562 APPROVED
3 467234 RESULTANT
4 784456 APPROVED
5 114667 APPROVED

I want to order all the records by id ASC but the one record with document_status RESULTANT has to be last so that it looks like this

id document_number document_status
1 12335 INFORMED
2 4562 APPROVED
4 784456 APPROVED
5 114667 APPROVED
3 467234 RESULTANT

This is what I tried but it completely ignores my second ORDER condition

SELECT 
l.id,
l.document_number,
l.document_status
FROM load_record l
ORDER BY l.id ASC, (l.document_status = 'RESULTANT')

It works if I remove the l.id ASC but then it will place the RESULTANT last but it won’t order the rest of the records by id ASC

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Inside the ORDER BY clause, the subsequent ordering fields (in your case, the second with respect to the first) are consulted only when the previous condition is tied, but in your case "l.id ASC" is never tied, so "l.document_status = ‘RESULTANT’" is never checked.

If you invert the fields inside your ORDER BY clause, it should work properly, because l.document_status = 'RESULTANT'* actually generates tied values, untied by l.id.

ORDER BY l.document_status = 'RESULTANT', l.id

Check the demo here.

Note: You can omit ASC, because it’s the default ordering value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading