SQL query to find record with ID not in another table Ask Question

SQL query to find record with ID not in another table Ask Question

I have two tables with binding primary keys in the database and I want to find a disjoint set between them. For example,

Table1

ID Name
1 John
2 Peter
3 Mary

Table2

ID Address
1 address2
2 address2

So how do I create a SQL query so I can fetch the row with ID from table1 that is not in table2? In this case, (3, Mary) should be returned.

PS: The ID is the primary key for those two tables.

ベストアンサー1

Try this

SELECT ID, Name 
FROM   Table1 
WHERE  ID NOT IN (SELECT ID FROM Table2)

おすすめ記事