Using SQL to Find records existing in one table but not in another

by Yang Yang on November 18, 2008

in SQL / MySQL Tips and Tutorials

The 2 tables are built with an identical data structure. Say you have records spread in both tables but neither of them are complete because both contain unique records. You need to consolidate the 2 tables into one with all unique records from each table.

NOT EXISTS clause is just the way to do it in SQL. Let’s try:

SELECT * FROM table2 WHERE NOT EXISTS (SELECT * FROM table1 WHERE id = table2.id)

This will select all records from table2 that don’t exist in table1 by id. To get a complete table of unique records from both table1 and table2, you need to just insert the results here into table1.

INSERT INTO table1 (SELECT * FROM table2 WHERE NOT EXISTS (SELECT * FROM table1 WHERE id = table2.id))

Related Posts

{ 2 comments… read them below or add one }

Adam December 15, 2008 at 2:40 am

This is really a nice way to get the results. I really appreciate your great post. please keep up the good work.

Reply

Yang Yang February 26, 2010 at 3:11 pm

Oh really

Reply

Leave a Comment

Previous post:

Next post: