I have a sql that is not very complex but sufficiently confusion that I question rather I have an equivalent or by coincident that the count are the same.
SQL1:
SELECT a, b
FROM table1
WHERE NOT EXISTS(
SELECT a, c
FROM TABLE2
WHERE table2.a != table1.a)
SQL2
SELECT table1.a, table1.b
FROM table1
LEFT JOIN table2 ON table2.a = table1.a
WHERE table2.a IS NULL
The count on the two are identical, but not sure if this is by chance, and I want to make sure the conversion do not change the original functionality.
The first query, as you have it, returns all rows of TABLE1 where
amatches all values ofain TABLE2. Therefore, it will return zero rows, unless there’s a single not-null value forain TABLE2, and that value exists in TABLE1. In that case, it will return as many rows as there are in TABLE1 with that value ofa.The second query is completely different. It will simply returns all rows of TABLE1 where
adoes not exist in TABLE2.So it’s “matches all” (query 1) vs. “does not match any” (query 2). The fact that you are getting the same number of rows is pure coincidence.
Your queries would be equivalent if you changed
!=for=in the first one, like this:That gets you values of
ain table1 that doesn’t exist in table2. This is EXACTLY the same as:As you have it though, they are NOT equivalent. You must change
!=for=in the first one to make them so.