Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check that a list of items exists in an SQL database column?

Tags:

sql

list

exists

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.

like image 456
brabster Avatar asked Jan 13 '09 20:01

brabster


People also ask

How do you check if data already exists in SQL database?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you check if data is present in database?

To check whether a particular value exists in the database, you simply have to run just a regular SELECT query, fetch a row and see whether anything has been fetched. Here we are selecting a row matching our criteria, then fetching it and then checking whether anything has been selected or not.


1 Answers

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.

like image 174
Kluge Avatar answered Nov 08 '22 11:11

Kluge