0

I have recursive query which returns some rows from hierarchical model. Kind Of:

files_array := ARRAY
   (WITH RECURSIVE files_to_parent AS (
          SELECT FileID, Name, ParentID
          FROM File
          WHERE FileID = file_id
       UNION ALL
          SELECT F.FileID, F.Name, F.ParentID
          FROM files_to_parent ftp, File F
          WHERE F.FileID = FTP.ParentID
    )
    SELECT Name FROM files_to_parent);

How can I reverse the result of the SELECT query?

PS: I cannot order by IDs, id of parent can be more or less then in child.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Serhiy
  • 1,332
  • 1
  • 16
  • 24

1 Answers1

1

You have to add an explicit ORDER BY clause to get a certain order:

WITH RECURSIVE files_to_parent AS (
      SELECT FileID, Name, ParentID,
             1 AS recursion_depth
      FROM File
      WHERE FileID = file_id
   UNION ALL
      SELECT F.FileID, F.Name, F.ParentID,
             ftp.recursion_depth + 1
      FROM files_to_parent ftp
         JOIN File F ON F.FileID = FTP.ParentID
)
SELECT Name
FROM files_to_parent
ORDER BY recursion_depth DESC;
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263