here is the query
SELECT * FROM customers
WHERE
NOT EXISTS
(
SELECT 1 FROM brochure_requests
WHERE brochure_requests.first_name = customers.customer_first_name AND
brochure_requests.last_name = customers.customer_last_name
)
This query works just fine but I am not sure why it works. In the NOT EXISTS part SELECT 1 what is the 1 for. When I ran this query
select 1 from test2
Here were the results:
1
-----
1
1
1
1
1
1
1
1
1
1
1
..
How does the not exists query work?
The compiler is smart enough to ignore the actual
SELECTin anEXISTS. So, basically, if it WOULD return rows because the filters match, that is all it cares about…theSELECTportion of theEXISTSnever executes. It only uses the EXISTS clauses for evaluation purposesI had this misconception for quite some time since you will see this
SELECT 1a lot. But, I have seen 42, *, etc….It never actually cares about the result, only that there would be one :). The key to keep in mind that SQL is a compiled language, so it will optimize this appropriately.You could put a 1/0 and it will not throw a divide-by-zero exception…thus further proving that the result set is not evaluated. This is shown in this SQLFiddle
Code from Fiddle:
And finally, more to your point, the
NOTsimply negates anEXISTS, saying to IGNORE any rows that match