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

Order table by two columns

Imagine that I have a table with entities and some of them have forks; the column fork stores the id of the parent ent or 0, if that ent doesn’t have a fork.

Table ents:

id  name        fork
1   Adidas      0
2   Betina      0
3   Shop Adidas 1
4   Shell       0
5   StoreAdidas 1
6   Shell 1     4

This is how I would like to get the results, ie, sorted by name but with the forks next with it’s parent:

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

id  name
1   Adidas
3   Shop Adidas
5   StoreAdidas
2   Betina
4   Shell
6   Shell 1

Is this possible with a mySQL query?

Thank you for you help

>Solution :

You can do:

select *
from t
order by case when fork <> 0 then fork else id end, 
         case when fork <> 0 then id else 0 end

See running example at DB Fiddle.

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