SQL For Programmers – Finding IN a List

TSQL - IN In the last SQL post, we looked at looking for content that was LIKE other content.  While this has its uses, it is limited in its ability to find more than one pattern.  So what if we want to find a record that matches more than one set of data?

That is what the IN clause is for.

The most common use of the IN clause is:

SELECT * FROM myTable
  WHERE fildName IN (comma,Separated,List)

So if you were looking for the records whose ID were equal to 1, 3, or 5, your query would look like:

SELECT * FROM myTable
  WHERE ID IN (1,1,5)

You could also use this with strings:

SELECT * FROM myTable
  WHERE firstName IN ('Dave','George','Frank')

The final form is using a sub-select.  I should warn you that most DBAs frown on this form since it does have performance issues.  But since most of us are just looking to get a job done, this may be just the ticket.  Given the alternatives, this is a simple way to find all the records in one table that are in another.  If there is a performance problem, then you can go looking for some alternative.

So, here is the syntax:

SELECT * FROM myTable
  WHERE firstName IN
    (SELECT firstName FROM myOtherTable
     WHERE someOtherCondition)

I recently used this in combination with NOT to find fields in the main table that didn’t have corresponding records in the sub-select table.

SELECT * FROM myTable
  WHERE firstName NOT IN
    (SELECT firstName FROM myOtherTable
     WHERE someOtherCondition)

Related Post

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear