My colleague John recently blogged about the unexpected results of using the T-SQL IN operator on a set that contains NULL. Here is another solution to the problem.There are three main ways to test for existence in another table, listed here in order of increasing performance
In general, the EXISTS operator will generate the most efficient query plan, and it also isn't subject to the very NULL pitfall that plagues the IN operator. The query that John posted:
SELECT COUNT(*)FROM TableTargetWHERE PrimaryKeyField NOT IN ( SELECT ForeignKeyField FROM TableSource WHERE ForeignKeyField IS NOT NULL)
Could be writtten like this:
SELECT COUNT(*)FROM TableTarget tWHERE NOT EXISTS ( SELECT * FROM TableSource WHERE ForeignKeyField = t.PrimaryKeyField)
Remember Me
a@href@title, i, strike, u
Copyright © 2003-2008 Falafel Software Inc.
Subscribe to Falafel Blogs
The opinions expressed herein are Falafel's employees own personal opinions and do not represent Falafel Software's view in any way in case they go bananas!