SQL For Programmers – Finding IN a List
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)
Other post in SQL For Programmers
- SQL For Developers - 9 Reasons to bother - August 13th, 2008
- MSSQL CREATE and DROP Database - SQL for Programmers - August 20th, 2008
- MSSQL CREATE TABLE - SQL For Programmers - August 22nd, 2008
- SQL For Programmers - ALTERing the TABLE - September 1st, 2008
- SQL For Programmers - Finding a String - September 3rd, 2008
- SQL For Programmers - Finding IN a List - September 8th, 2008
- SQL For Programmers - Stored Procedures (Better than LINQ) - September 10th, 2008
- SQL For Programmers - Stored Procedure Basics - September 16th, 2008
- Basic SQL Commands - SQL For Programmers - September 18th, 2008
- SQL IF/WHILE Blocks - SQL For Programmers - September 30th, 2008
- SQL WHILE - SQL For Programmers - October 2nd, 2008
- Temporary Tables - SQL For Programmers - October 7th, 2008
- SQL CURSOR - SQL For Programmers - October 13th, 2008
- SQL CURSOR Performance - SQL For Programmers - October 22nd, 2008
- Random in SQL - SQL For Programmers - November 4th, 2008
- SQL - Filtering WHERE condition on two rows - November 26th, 2008
- SQL - Transactions - April 15th, 2009
- SQL For Programmers – New Question - July 6th, 2009
- SQL SELECT CASE Instead of IIF - October 20th, 2009
Other Related Items:
3 in 1 iPod Charger Kit, Home/Travel Charger, Car Charger, Retractable USB kit.Power to the music with a car charger adapter that allows using your iPod on the road. IC Chip Technology to prevent back-flow current and your iPod f... Read More >
Nick Jr. Favorites - Vol. 6Movie DVD









