Question

If I have a list of items, say

apples
pairs
pomegranites

and I want to identify any that don't exist in the 'fruit' column in an SQL DB table.

  • Fast performance is the main concern.
  • Needs to be portable over different SQL implementations.
  • The input list could contain an arbitrary number of entries.

I can think of a few ways to do it, thought I'd throw it out there and see what you folks think.

Was it helpful?

Solution

Since the list of fruits you are selecting from can be arbitrarily long, I would suggest the following:

create table FruitList (FruitName char(30))
insert into FruitList values ('apples'), ('pears'), ('oranges')

select * from FruitList left outer join AllFruits on AllFruits.fruit = FruitList.FruitName
where AllFruits.fruit is null

A left outer join should be much faster than "not in" or other kinds of queries.

OTHER TIPS

Make the search list into a string that looks like '|fruit1|fruit2|...fruitn|' and make your where clause:

where
  @FruitListString not like '%|' + fruit + '|%'

Or, parse the aforementioned string into a temp table or table variable and do where not in (select fruit from temptable). Depending on the number of items you're searching for and the number of items being searched, this method could be faster.

if exists(select top 1 name from fruit where name in ('apples', 'pairs', 'pomegranates'))
  PRINT 'one exists'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top