Wednesday, February 11, 2009

Finding records in one table that are NOT referenced in another table

Sometimes we have one table records referencing records in another table. What if we want to find all the records in one table that are not referenced by ANY record in the other table?
For example, say we have one record of people's names: a table called PEOPLE with two fields: ID and NAME. The other table holds all nicknames of the people in the first table. It has three fields: ID, PeopleID, and Nickname. Values for these table could be:

PEOPLE
ID Name
--------
1 Michael

NICKNAMES
ID PeopleID Nickname
------------------------
1 1 Micky
2 1 Mick

Now let's say we want to find all people who DON'T have any nick name.
Here is how we do that:

SELECT PEOPLE.ID, PEOPLE.Name
FROM PPEOPLE LEFT OUTER JOIN NICKNAMES
ON PEOPLE.ID = NICKNAMES.PeopleID
WHERE NICKNAME.PeopleID IS NULL

First we are using outer join to make sure we get these records, even though the matching records in the other table to not exist.

Then we use the IS NULL condition. Note that '= NULL' will not work (I know, I tried it first...)

Now we have all the people with not even one nickname.

No comments:

Post a Comment