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

SQL: Order on the basis of values of multiple columns

I have a table that includes 3 columns – chat, video, and call. They can have values 0 or 1.

Now I want to order results such that if all three (chat, video, and call) are 0, then those rows are in the last else they have random order.

What will be the SQL query in this case? I am using MySQL.

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 :

You can use conditional ordering using a CASE clause in the ORDER BY clause.

For example:

select *
from t
order by case when chat + video + `call` = 0 then 1 else 0 end

If randon order is really important you can change the ordering as shown below:

select *
from t
order by case when chat + video + `call` = 0 
                 then 1 + rand() 
                 else 0 + rand() 
         end
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