You need to get a sample containing the parents and a list of children under it. Tried to use WITH, but I receive not what is necessary

WITH PatronCon (id, parent_id) AS (SELECT id, parent_id FROM PatronContact WHERE parent_id IS NULL UNION ALL SELECT t1.id, t1.parent_id FROM PatronContact t1 JOIN PatronCon t2 ON t1.parent_id = t2.id ) SELECT * FROM PatronCon 

As a result, from a table with such data

 id parent_id --- ------- 1 null 2 1 3 1 4 null 5 4 6 4 7 1 8 4 

Need to get such an answer

 id parent_id --- ------- 1 null 2 1 3 1 7 1 4 null 5 4 6 4 8 4 

    1 answer 1

     ORDER BY CASE WHEN parent_id IS NULL THEN id ELSE parent_id END, parent_id, id