1

I have following MySQL db table filled with data:

|id|parentId|position
|20|NULL    |1
|21|NULL    |2
|22|NULL    |3
|23|21      |1
|24|21      |2

Is it possible to sort it to get final result as:

|id|parentId|position
|20|NULL    |1
|21|NULL    |2
|23|21      |1
|24|21      |2
|22|NULL    |3

As you may notice, position inside parent starts from 1.

So I want it sorted by three columns: id, parentId and position. Any ideas?

2 Answers 2

3

The sorting logic you want is to sort first by the parentId group. This can be obtained using COALESCE(parentId, id). In other words, if the parentId is present, then use it, otherwise take the id, which must also be the parent. Then, within parent group, sort NULLs first. Finally, within those two groups, sort by position.

SELECT *
FROM yourTable
ORDER BY
    COALESCE(parentId, id),
    parentID,
    position;

enter image description here

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

I think you want something ?

ORDER BY IFNULL(parentId, id), parentId, position 

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.