Search code examples
sqlrelational-division

Record that is related to all records of other table in SQL


Let's say we have three tables in a relational database:

Person {id, name}
Obstacle {id, name}
Person_overcomes_obstacle {person_id, obstacle_id}

I want to write a query that tells me if at least one person has overcome all obstacles. Ideas?


Solution

  • I notice that I was the only person to use the natural table alias for Person_overcomes_obstacle!

    You need a relational division query for this.

    You can either count up the obstacles and the matching records in Person_overcomes_obstacle and return ones where the 2 numbers match or look at it another way as finding people for which there is no obstacle that they haven't overcome.

    SELECT p.id, p.name /*Or use COUNT(*) or wrap in Exists 
                         if you don't care about ids and names*/
    FROM Person p
    WHERE NOT EXISTS
       (SELECT * FROM Obstacle o
        WHERE NOT EXISTS 
        (
           SELECT * FROM Person_overcomes_obstacle poo
           WHERE poo.person_id = p.id and o.id = poo.obstacle_id
        )
    )