I’am dealing with a pretty basic SQL query, but I cannot understand why the non matching records are not represented with the null values in right table.
I have table A and table B with a composite key and some data in table B that I know that they do not match the key in table A. However, the result set returns only rows with matching keys without non matching (null) records.
SELECT * FROM TableA a LEFT JOIN TableB b ON a.Field1 = b.Field1 AND a.Field2 = b.Field2 WHERE b.Field1 IS NULL
I was expecting to see records from table A and those records from table B that do not match to be represented by Nulls.
EDIT************************************************************
Link with sample data and tables:
https://drive.google.com/file/d/1PNlyqO4mwMBOGgQnWVlduiDKaDjSaE8v/view?usp=sharing
Last record in TableB should be seen because value for Field5 differs from value in TableA.
Advertisement
Answer
The problem with your attempt is that you start with the records in TableA
then LEFT JOIN
against TableB
. This forces the engine to only display records from TableA
, with additional rows/columns from TableB
if they match, but not records from TableB
that aren’t on TableA
.
Either you want to reverse the join order:
SELECT * FROM TableB b LEFT JOIN TableA a ON a.Field1 = b.Field1 AND a.Field2 = b.Field2 WHERE a.Field1 IS NULL -- records from A table shouldn't exist
Or as RIGHT JOIN
SELECT * FROM TableA a RIGHT JOIN TableB b ON a.Field1 = b.Field1 AND a.Field2 = b.Field2 WHERE a.Field1 IS NULL -- records from A table shouldn't exist
Or a FULL JOIN
if you want records from both displayed, even if no match on the other table (no WHERE
clause):
SELECT * FROM TableA a FULL JOIN TableB b ON a.Field1 = b.Field1 AND a.Field2 = b.Field2