Customers Holidays id | name customer_id | start | end ---+------ ------------+--------+------ 1 | Peter 1 | 5 | 10 2 | Simon 1 | 15 | 20 3 | Mary 2 | 5 | 20
What’s a working SQL query that gives me all customers without holidays on a specific date? E.g. date=12
- Peter
- Mary
Is this even manageable with a simple SQL join, or do I need to use sub-queries?
First create a query that finds the opposite of what you want: the customers who do have a holiday on that specific date:
Result:
Then join this result back to the customer table and select the results where the join fails:
Result:
Note that a JOIN isn’t the only alternative here. You could also use
NOT EXISTS,NOT INorEXCEPT. Since you didn’t specify which database, I chose JOIN because it is a portable and efficient way to do it in all the major relational databases.The test data I used (taken from the question):