Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So I have two tables: directors, and movies.

Directors contain: ID, name, dob, gender
Movies contain: ID, name, director_id, release_date, and release_year (foreign key: director_id)

I have to find out which directors do not have a movie in the movies table but I don't know how to do this. please help.
Posted

There are a lot of ways for querying this but I think NOT EXISTS clause is one of the most verbose.

Consider the following example:
SQL
SELECT *
FROM Directors d
WHERE NOT EXISTS (SELECT 1
                  FROM   Movies m
                  WHERE  m.director_id = d.id)

The subquery in the NOT EXISTS clause is a correlated subquery. In other words, logically for each row in the Directors table the subquery is run and end the databses checks if the subquery returns a row or not using the id from the directors row.

For more explanations, have a look at
- Subquery Fundamentals[^]
- Correlated Subqueries[^]

Another way would be to not use a correlated subquery but fetch the director id's before hand. In such case the query could look something like
SQL
SELECT *
FROM Directors d
WHERE d.Id NOT IN (SELECT DISTINCT m.director_id
                  FROM   Movies m)

In this example the list of director id's is created first and for each movie the query checks that the id of a director is not in the list. The keyword DISTINCT is used to eliminate duplicates since it's sufficient that each director id is listed only once regardless of how many movies one has.

For more information about DISTINCT see SELECT Clause (Transact-SQL)[^]
 
Share this answer
 
A bit performance optimized version of the SQL would be like

SQL
SELECT *
FROM   DIRECTORS D
LEFT OUTER JOIN MOVIES M ON D.DIRECTOR_ID = M.DIRECTOR_ID
WHERE M.DIRECTOR_ID IS NULL


Sub Queries have performance cost because they evaluate over each row.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900