i’m constructing an SQL query (SQLITE) to check for dates in two tables that don’t exist in a third table. In the code below, tables 2 and 3 contain all valid dates and the intent is to get a list of dates in table 1 that don’t exist in 2 or 3 so they can be removed.
When just comparing just 2 tables, the EXCEPT argument works well.
SELECT date1 FROM table1
EXCEPT
SELECT date2 FROM table2
works a treat.
I would have thought that surrounding the 2nd part of the EXCEPT argument in parentheses for more complex arguments would do it but
SELECT date1 FROM table1
EXCEPT (
SELECT date2 FROM table2
UNION
SELECT date3 FROM table3
)
generates a syntax error… (which disappears when i remove the parentheses but then i suspect the result would be from (line 1 except line 2) union line 3, which would be wrong?
Actually found the correct answer - for anyone else that needs this, the correct syntax is:
SELECT date1 FROM table1
EXCEPT
SELECT * FROM (
SELECT date2 FROM table2
UNION
SELECT date3 FROM table3
)
-- returns all dates in table1 that don't exist in either table2 or table3
There’s about a million ways to skin a cat… but always good to know more
So, looking up EXISTS, the definition is “The EXISTS operator is a logical operator that checks whether a subquery returns any row.” - a boolean result.
Keeping in mind i want to return a list of values in one query that don’t exist in another query as my example above, how would I use EXISTS for this?
(it’s academic as the EXCEPT operator does exactly that - semantically similar to NOT IN - but can’t get my head around how you would use EXISTS in my example above and am now intrigued )
So in terms of my specific problem, using the simpler version with just two tables, to find all dates in table 1 except for those in table 2, using EXISTS would be:
SELECT date1 FROM table1
WHERE NOT EXISTS (
SELECT date2 FROM table2
WHERE table1.date1 = table2.date2
)
Yep it works just fine – but i still prefer the EXCEPT semantics (ie all values in query1 except from those in query2). I’ll put that down to not being an (SQL) old guy