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

  • Home
  • SEARCH
  • 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 279543
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:02:29+00:00 2026-05-12T05:02:29+00:00

I have a tree in my database that is stored using parent id links.

  • 0

I have a tree in my database that is stored using parent id links.

A sample of what I have for data in the table is:

id | name        | parent id
---+-------------+-----------
0  | root        | NULL
1  | Node 1      | 0
2  | Node 2      | 0
3  | Node 1.1    | 1
4  | Node 1.1.1  | 3
5  | Node 1.1.2  | 3

Now I would like to get a list of all the direct descendants of a given node but if none exist I would like to have it just return the node itself.

I want the return for the query for children of id = 3 to be:

children
--------
4
5

Then the query for the children of id = 4 to be:

children
--------
4

I can change the way I am storing the tree to a nested set but I don’t see how that would make the query I want possible.

  • 1 1 Answer
  • 1 View
  • 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-12T05:02:29+00:00Added an answer on May 12, 2026 at 5:02 am

    In new PostgreSQL 8.4 you can do it with a CTE:

    WITH RECURSIVE q AS
            (
            SELECT  h, 1 AS level, ARRAY[id] AS breadcrumb
            FROM    t_hierarchy h
            WHERE   parent = 0
            UNION ALL
            SELECT  hi, q.level + 1 AS level, breadcrumb || id
            FROM    q
            JOIN    t_hierarchy hi
            ON      hi.parent = (q.h).id
            )
    SELECT  REPEAT('  ', level) || (q.h).id,
            (q.h).parent,
            (q.h).value,
            level,
            breadcrumb::VARCHAR AS path
    FROM    q
    ORDER BY
            breadcrumb
    

    See this article in my blog for details:

    • PostgreSQL 8.4: preserving order for hierarchical query

    In 8.3 or earlier, you’ll have to write a function:

    CREATE TYPE tp_hierarchy AS (node t_hierarchy, level INT);
    
    CREATE OR REPLACE FUNCTION fn_hierarchy_connect_by(INT, INT)
    RETURNS SETOF tp_hierarchy
    AS
    $$
            SELECT  CASE
                    WHEN node = 1 THEN
                            (t_hierarchy, $2)::tp_hierarchy
                    ELSE
                            fn_hierarchy_connect_by((q.t_hierarchy).id, $2 + 1)
                    END
            FROM    (
                    SELECT  t_hierarchy, node
                    FROM    (
                            SELECT  1 AS node
                            UNION ALL
                            SELECT  2
                            ) nodes,
                            t_hierarchy
                    WHERE   parent = $1
                    ORDER BY
                            id, node
                    ) q;
    $$
    LANGUAGE 'sql';
    

    and select from this function:

    SELECT  *
    FROM    fn_hierarchy_connect_by(4, 1)
    

    The first parameter is the root id, the second should be 1.

    See this article in my blog for more detail:

    • Hierarchical queries in PostgreSQL

    Update:

    To show only the first level children, or the node itself if the children do not exist, issue this query:

    SELECT  *
    FROM    t_hierarchy
    WHERE   parent = @start
    UNION ALL
    SELECT  *
    FROM    t_hierarchy
    WHERE   id = @start
            AND NOT EXISTS
            (
            SELECT  NULL
            FROM    t_hierarchy
            WHERE   parent = @start
            )
    

    This is more efficient than a JOIN, since the second query will take but two index scans at most: the first one to make sure to find out if a child exists, the second one to select the parent row if no children exist.

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

Sidebar

Ask A Question

Stats

  • Questions 309k
  • Answers 309k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Your MSVC build has no optimizations on. Turn them on,… May 13, 2026 at 9:54 pm
  • Editorial Team
    Editorial Team added an answer The || operator is a logical operator. The semantics of… May 13, 2026 at 9:54 pm
  • Editorial Team
    Editorial Team added an answer You could compare DOM elements. Remember that jQuery selectors return… May 13, 2026 at 9:54 pm

Related Questions

Say I have a file based data structure such as a B+ Tree. My
I have a stored procedure which filters based on the result of the DATEADD
I'm planning software that's an OLAP application at its heart (it helps analyse metering
I have a fixed-length data file need to persistence into database. I use a

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.