I had a strange error where I did something like the following:
SELECT *
FROM table1
WHERE NAME COLLATE LATIN1_General_CI_AS NOT IN (select name FROM table2)
Name was a nvarchar(50) null. Table2 had null values in the name column. It would then match names that did not exist in table2 because of the null values. Meaning that this would return 0 results. And if I did:
SELECT *
FROM table1
WHERE NAME COLLATE LATIN1_General_CI_AS NOT IN (
select name FROM table2 where name is not null
)
I would get some results.
One table had collation Danish_Norwegian_CI_AS and the other one latin1. Maybe the COLLATE is the source of the problem?
Can anyone explain why this happens? Maybe something with set theory?
It has nothing to do with collation. Try
set ansi_nulls offand the first query will work as you expected.The reason is that when you try to compare something to NULL (e.g. a = NULL or a <> NULL) the result is UNKNOWN and the entire query fails. If you set
ansi_nullstooffthen the same comparison evaluates to TRUE or FALSE and the query “works”.In other words:
means
WHERE the last part
a <> nullevaluates to UNKNOWN and the query fails to return any rows.