Example A
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.key = table2.key WHERE table2.key IS NULL;
Example B
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.key = table2.key AND table2.key IS NULL;
Would the two SQL queries above be logically equivalent or what is the point of filtering within the ON
?
Advertisement
Answer
Example1 – WHERE
clause condition filters the final result so your example1 returns data from table1
for which matching data is not present in table2
as left join
is based on key
and after that where
condition filters all the records that have no matching key
in the table2
– you will find less than or equal to total table1
record in the result
Example2 – Condition in the ON
is used to join two tables so your example2 will give you all the data from table1
and only matching data from table2
. But as you have used conflicting condition in the ON
clause (ON table1.key = table2.key AND table2.key IS NULL
), your example2 will return all data for table1
and no data for table2
(null
in all columns for table2) – final result will have number of records equal to number of records in table1
.