[sql] SQL query to find record with ID not in another table

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

  • Table1 has columns (ID, Name) and sample data: (1 ,John), (2, Peter), (3, Mary)
  • Table2 has columns (ID, Address) and sample data: (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.

Thanks in advance.

This question is related to sql database postgresql

The answer is


Try this

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

Similar questions with sql tag:

Similar questions with database tag:

Similar questions with postgresql tag: