sqldatabasesubqueryamazon-redshiftsql-except

How to avoid selection of rows of parents that don't have a child, if they have children in other rows?


I want to avoid selecting the cases where there is a blank child, but only where a parent-child relationship already exists. So in this example, A-D would stay but the empty rows with A should get removed. As C doesn't have any children in any row, it will remain.

Input:

parent     child
A          D
A
A
B          E
B          F
C

Desired Output:

parent     child
A          D
B          E
B          F
C

What I've tried:

SELECT parent, child
FROM my_table
WHERE child NOT NULL
EXCEPT 
SELECT parent, child
FROM my_table
-- condition to check existing relationships if they exist

Solution

  • maybe use a query like below. this uses exists keyword to check presence of any other not null child

    SELECT parent, child
    FROM my_table t
    WHERE child is NOT NULL
    OR NOT EXISTS 
    (
    SELECT 1 FROM my_table p Where p.parent=t.parent and p.child is Not null
    )