Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
postgresql procedure for finding hie parent chain

I am new to postgresql and need a little help.I have a table named products

ID Product Parent_ID
1  laptop   Null
2  Camera   1
3  Iphone   1
4  Mouse    2
5  Printer  2
6  Scanner  3
7  HardDisk 3

I want to create a function in postgres to get the hierarchy of the parent chain of any value i pass like if i pass 4 then my output should be

id parent_id
1  Null
2  1
4  2
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I would suggest to use "recursive with" clause. Kindly check below query.

WITH RECURSIVE recursiveTable AS (
SELECT id, parent_id  
FROM table_name
WHERE id = 4  -- you can pass an id here to get the output
UNION ALL
SELECT t.id, t.parent_id
FROM table_name t                  
JOIN recursiveTable rt ON t.id = rt.parent_id 
)
SELECT * FROM recursiveTable

You can read more about recursive with clause on it official websites. Or you can check couple of examples.

Here is one link http://technobytz.com/recursive-query-evaluation-postgresql.html

Function: Try this

CREATE OR REPLACE FUNCTION function_name(param_id INT) 
RETURNS TABLE (
id INT,
parent_id INT
) 
AS $$
BEGIN
RETURN QUERY WITH RECURSIVE recursiveTable AS (
SELECT t.id, t.parent_id  
FROM table_name t
WHERE t.id = param_id  -- you can pass an id here to get the output
UNION ALL
SELECT t.id, t.parent_id 
FROM table_name t                  
JOIN recursiveTable rt ON t.id = rt.parent_id
)
SELECT * FROM recursiveTable ;

END; $$ 

LANGUAGE 'plpgsql';

Function Execution: select * from function_name(4)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!