Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7046903
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T02:42:22+00:00 2026-05-28T02:42:22+00:00

I’m using PostgreSQL’s Ltree module for storing hierarchical data. I’m looking to retrieve the

  • 0

I’m using PostgreSQL’s Ltree module for storing hierarchical data. I’m looking to retrieve the full hierarchy sorted by a particular column.

Consider the following table:

  votes | path  | ...
 -------+-------+-----
      1 | 1     | ...
      2 | 1.1   | ...
      4 | 1.2   | ...
      1 | 1.2.1 | ...
      3 | 2     | ...
      1 | 2.1   | ...
      2 | 2.1.1 | ...
      4 | 2.1.2 | ...
    ... | ...   | ...

In my current implementation, I’d query the database with SELECT * FROM comments ORDER BY path, which would return the whole tree:

Node 1
-- Node 1.1
-- Node 1.2
---- Node 1.2.1
Node 2
-- Node 2.1
---- Node 2.1.1
---- Node 2.1.2

However, I want to sort by votes (not by id, which is what sorting by path amounts to). Each depth level needs to be independently sorted, with the correct tree structure kept intact. Something that would return the following:

Node 2
-- Node 2.1
---- Node 2.1.2
---- Node 2.1.1
Node 1
-- Node 1.2
---- Node 1.2.1
-- Node 1.1

Postgres’ WITH RECURSIVE might be appropriate, but I’m not sure. Any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T02:42:23+00:00Added an answer on May 28, 2026 at 2:42 am

    You were on the right track with WITH RECURSIVE.

    Solution with recursive CTE

    WITH RECURSIVE t AS (
        SELECT t.votes
             , t.path
             , 1::int AS lvl
             , to_char(t2.votes, 'FM0000000')  AS sort
        FROM   tbl t
        JOIN   tbl t2 ON t2.path = subltree(t.path, 0, 1)
    
        UNION ALL
        SELECT t.votes
             , t.path
             , t.lvl + 1
             , t.sort || to_char(t2.votes, 'FM0000000')
        FROM   t
        JOIN   tbl t2 ON t2.path = subltree(t.path, 0, t.lvl + 1)
        WHERE  nlevel(t.path) > t.lvl
        )
    SELECT votes, path, max(sort) AS sort
    FROM   t
    GROUP  BY 1, 2
    ORDER  BY max(sort), path;
    

    Major points

    • The crucial part is to replace every level of the path with the value of votes. Thereby we assemble one column we can ORDER BY at the end. This is necessary, because the path has an unknown depth and we cannot order by an unknown number of expressions in static SQL.

    • In order to get a stable sort, I convert votes to a string with leading zeroes using to_char(). I use seven digits in the demo, which works for vote values below 10.000.000. Adjust according to your maximum vote count.

    • In the final SELECT I exclude all intermediary states to eliminate duplicates. Only the last step with max(sort) remains.

    • This works in standard SQL with a recursive CTE, but is not very efficient for large trees. A plpgsql function that recursively updates the sort path in a temporary table without creating temporary dupes might perform better.

    • Only works with the additional module ltree installed, which provides the functions subltree() and nlevel(), as well as the ltree data type.

    My test setup, for review convenience:

    CREATE TEMP TABLE tbl(votes int, path ltree);
    INSERT INTO tbl VALUES
      (1, '1')
    , (2, '1.1')
    , (4, '1.2')
    , (1, '1.2.1')
    , (3, '2')
    , (1, '2.1')
    , (2, '2.1.1')
    , (4, '2.1.2')
    , (1, '2.1.3')
    , (2, '3')
    , (17, '3.3')
    , (99, '3.2')
    , (10, '3.1.1')
    , (2345, '3.1.2')
    , (1, '3.1.3')
    ;
    

    PL/pgSQL table function doing the same

    Should be faster with huge trees.

    CREATE OR REPLACE FUNCTION f_sorted_ltree()
      RETURNS TABLE(votes int, path ltree)
      LANGUAGE plpgsql VOLATILE AS
    $func$
    DECLARE
       lvl integer := 0;
    BEGIN
       CREATE TEMP TABLE t ON COMMIT DROP AS
       SELECT tbl.votes
            , tbl.path
            , ''::text AS sort
            , nlevel(tbl.path) AS depth
       FROM   tbl;
    
       -- CREATE INDEX t_path_idx ON t (path);   -- beneficial for huge trees
       -- CREATE INDEX t_path_idx ON t (depth);
    
       LOOP
          lvl := lvl + 1;
    
          UPDATE t SET sort = t.sort || to_char(v.votes, 'FM0000000')
          FROM  (
             SELECT t2.votes, t2.path
             FROM   t t2
             WHERE  t2.depth = lvl
             ) v
          WHERE  v.path = subltree(t.path, 0 ,lvl);
    
          EXIT WHEN NOT FOUND;
       END LOOP;
    
       -- Return sorted rows
       RETURN QUERY
       SELECT t.votes, t.path
       FROM   t
       ORDER  BY t.sort;
    END
    $func$;
    

    Call:

    SELECT * FROM f_sorted_ltree();
    

    Read in the manual about setting temp_buffers.

    I would be interested which performs faster with your real life data.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a jquery bug and I've been looking for hours now, I can't
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.