Using the IN clause

Using the IN clause with a WHERE is a simple way to tidy up a query, making it much more readable, and potentially increasing query performance.

SELECT *
FROM Person
WHERE PersonId IN (1, 2, 3)

The above is equivalent to

SELECT *
FROM PERSON
WHERE PersonId = 1 OR
      PersonId = 2 OR
      PersonId = 3

As you can see, the second query contains a lot more syntax for the same result.

You can also use a Noncorrelated Subquery within the brackets of the IN clause, as below:

SELECT *
FROM Person
WHERE PersonId IN (
                   SELECT DISTINCT
                          PersonId
                   FROM Orders
                  )

The above code would return all Person records, who have a record in the Orders table.

Alternatively, you can use NOT IN to exclude specific records.

SELECT *
FROM Person
WHERE PersonId NOT IN (1, 2, 3)

This would return all records that do not have a PersonId of 1, 2, or 3.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)