Ask the Expert

Finding rows that exist in one table but not another

How do you find all the rows in one table that do not exist in another table?

Requires Free Membership to View

There are two ways to find rows that exist in one table but not another.

The first method is to use a subquery:

SELECT id FROM table1 WHERE id NOT IN (SELECT id FROM table2);

This approach has the advantage of being more obvious to the casual reader, at the cost of portability (you need MySQL version 4.1 to use subqueries).

Alternately, you can use a left join:

SELECT table1.id FROM table1 LEFT JOIN table2 ON (table1.id = table2.id) WHERE table2.id IS NULL;

This approach may execute faster than a subquery, and works in all versions of MySQL. It may lose clarity for those readers not familiar with table joins and null values.

This was first published in July 2006

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: