Free Information Technology Magazines and eBooks

Thursday, February 12, 2009

SQL: SELECT All records from one table where not in the other table

There are time we need to look for records on a table which are not existing on another table. This can be achieved using LEFT JOIN query. Below is an example scenario:

SCENARIO:
Get all records on T_ManifestResponses which status equal to zero then send an email to the owner of that transaction. After sending an email, insert a record to T_ManifestEmailEvent.

PROBLEM:
Do not include records on T_ManifestResponses which are already in T_ManifestEmailEvent. The objective is to avoid sending same email for records that were already processed before.

SOLUTION:
SELECT a.ManifestNo, a.RegistryNo, a.CDFile, b.SentEmailOn
FROM T_ManifestResponses a LEFT OUTER JOIN
T_ManifestEmailEvent b ON a.RegistryNo = b.RegistryNo AND
a.ManifestNo = b.ManifestNo AND
a.CDFile =b.CDFile
WHERE a.Status=0 AND b.SentEmailOn IS NULL



The trick here is by joining the two tables (a and b) using LEFT JOIN then checking for NULL values on any fields on the second table (b). SQL engine will get all transactions from table (a) and will merge transactions from table (b) if there is any. If no record from table (b) exist, then fields coming from table (b) will all be NULL values.

1 comments:

Enow Mbi said...

very good code.It works perfectly i got the chime but i resolved it thanks a million.