Search code examples
sqlpostgresqlhierarchical-datarecursive-query

Select all parents having a child with specific property


Consider the following pseudo tables:

Parent(id)
Child(id, parent_id, property)

How can I select all parents having a child where property has a specific value in PostgreSQL?


Solution

  • You can use exists:

    select p.*
    from parent p
    where exists (select 1
                  from child c
                  where c.parent_id = p.id and c.property = ?
                 );