Home > database >  how can I order my SQL query by the next-in-line parent's ID?
how can I order my SQL query by the next-in-line parent's ID?

Time:10-29

I have a table called stages like this:

stageID stage parentStageID
1 Stage1 NULL
2 Stage2 3
3 Substage1 1
4 Stage3 2

The parentStageID references the stageID of its parent in the same table. I'm trying to write a query that selects everything in the table and sorts them by order of the next child in line. The NULL parentStageID being the first in the sequence, followed by the next stage with parentStageID equal to the last stageID.

The ordered table results like this:

stageID stage parentStageID
1 Stage1 NULL
3 Substage1 1
2 Stage2 3
4 Stage3 2

I'm not entirely sure how to go about doing this, but from other similar stack posts I was trying to do this with:

SELECT * FROM stages ORDER BY COALESCE(`parentStageID`, `stageID`), `parentStageID` IS NOT NULL, `stageID`;

Here I have this small enter image description here

This code might not be best for huge data, but it will give the expected output.

  • Related