I am sure making a silly mistake but I can't figure what:
In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM.
When I run this query:
SELECT idCustomer FROM reservations WHERE idCustomer NOT IN (SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2)
I get 0 results.
But
SELECT idCustomer FROM reservations
returns 152.000 results and the "NOT IN" part:
SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2
returns only 284 rows
The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.
An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
We can use both SQL Not Equal operators <> and != to do inequality test between two expressions. Both operators give the same output. The only difference is that '<>' is in line with the ISO standard while '!=
SQL NOT IN operator is used to filter the result if the values that are mentioned as part of the IN operator is not satisfied.
SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2 and idCustomer is not null
Make sure your list parameter does not contain null values.
Here's an explanation:
WHERE field1 NOT IN (1, 2, 3, null)
is the same as:
WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.
It's always dangerous to have NULL
in the IN
list - it often behaves as expected for the IN
but not for the NOT IN
:
IF 1 NOT IN (1, 2, 3, NULL) PRINT '1 NOT IN (1, 2, 3, NULL)' IF 1 NOT IN (2, 3, NULL) PRINT '1 NOT IN (2, 3, NULL)' IF 1 NOT IN (2, 3) PRINT '1 NOT IN (2, 3)' -- Prints IF 1 IN (1, 2, 3, NULL) PRINT '1 IN (1, 2, 3, NULL)' -- Prints IF 1 IN (2, 3, NULL) PRINT '1 IN (2, 3, NULL)' IF 1 IN (2, 3) PRINT '1 IN (2, 3)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With