Quantcast
Channel: andrewlocatelliwoodcock » SQL
Viewing all articles
Browse latest Browse all 7

Using SQL and LEFT JOINs to find missing data

$
0
0

It’s not unusual when working with data-driven applications to be asked to produce ad-hoc exception reoprst of the type: there should a at least one row in TableB for each row in TableA – can you tell me any rows in TableA that do not have at least one corresponding row in TableB?

How do you find something that’s not there?!

Our old friend the LEFT JOIN to the rescue. We already know from this post, that we can use LEF T JOINs to return every row from one table and any matching row from another and this is an extension of the same problem: in this case, we are looking specifically for every row in table A that does not have a matching row in table B.

Here’s how to do it:

SELECT
      a.Id
FROM
      TableA a
LEFT JOIN TableB b ON a.Id = b.Id
WHERE
      b.Id IS NULL

So, we’re returning everything in TableA, anything matching from TableB but then limiting the resultset to only those rows in TableA that DO NOT have a match in TableB. We do that with the statement:

WHERE b.Id IS NULL

This works because the database is returning all rows from TableA and matching rows from TableB but it still has to return something in the case where there are no matching rows in TableB: the special value NULL meaning “unknowable”. What our WHERE clause is saying is “only return those rows in TableA where the matching row in TableB is unknowable”, i.e. where we don’t have a matching row!

Simples.


Filed under: Databases, mySQL, SQL, SQL Server, T-SQL Tagged: Databases, LEFT JOIN, SQL

Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images