I have a following table:
+----+-----------+------+
| id | parent_id | name |
+----+-----------+------+
| 1 | 4 | d |
| 2 | null | a |
| 3 | 2 | b |
| 4 | null | c |
+----+-----------+------+
parent_id points to a record in the same table. If parent_id is null it a root element.
Data can be in random order. Is it possible to order my select so the output will be in the order they would be in an expanded tree: A, B, C, D?
Or is it better to select it in random order and order it programmatically by iterating the result, finding the first root element and then iterating the whole result again to find all the children for that element and etc?