Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CTE, why is an empty table returned?

I’m using a Postgresql database and I’m trying to get a tree using a CTE:

Alice
...Bob
......Dave
......Emma
...Cindy
......Fred
......Gail

Doesn’t output any errors. There is nothing in the output, where did I go wrong?

Database

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CREATE TABLE org(
  name TEXT PRIMARY KEY,
  boss TEXT REFERENCES org
);

INSERT INTO org VALUES('Alice',NULL);
INSERT INTO org VALUES('Bob','Alice');
INSERT INTO org VALUES('Cindy','Alice');
INSERT INTO org VALUES('Dave','Bob');
INSERT INTO org VALUES('Emma','Bob');
INSERT INTO org VALUES('Fred','Cindy');
INSERT INTO org VALUES('Gail','Cindy');

My request:

WITH RECURSIVE under_alice AS (select name, boss, 0 AS level FROM org 
     where boss = null
    UNION ALL
    SELECT org.name, org.boss, under_alice.level+1
      FROM org JOIN under_alice ON org.boss=under_alice.name
  )
SELECT * FROM under_alice;

>Solution :

WITH RECURSIVE under_alice AS
(
  select name, boss, 0 AS level FROM org 
     where boss IS NULL 
 UNION ALL
  SELECT org.name, org.boss, under_alice.level+1
  FROM org JOIN under_alice ON org.boss=under_alice.name
)
SELECT * FROM under_alice

Please take a look on where boss IS NULL. Here is the issue in your query

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading