Quackit Logo

FREE Hosting!

With every domain name you register with ZappyHost, you get FREE hosting.

$1.99 Domain Names

With every new non-domain purchase thru ZappyHost, you get a domain name for only $1.99.

SQL In

Print Version

The SQL IN operator assists you in providing multiple values in your WHERE clause. This can provide very useful when you need to compare your value to a list of values. Often this list could be the result of a query from another table.

SQL Syntax

SELECT * FROM table_name
WHERE column_name IN (value1,value2,...)

Example

SQL statement

SELECT * FROM Individual
WHERE LastName IN ('Simpson','Ozzbourne','Flinstone')

Source Table

IdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike

Result

IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
4OzzyOzzbournesabbath

You might have noticed that this returns the same result as the following SQL statement:

SELECT * FROM Individual
WHERE LastName = 'Simpson'
OR LastName = 'Ozzbourne'
OR LastName = 'Flinstone'

Yes, we could just have easily used that statement but the SQL IN statement is more concise.

SQL IN and Subqueries

Now, where the SQL IN operator becomes really useful is when you need to compare a value against the result of another query.

For example, lets say we have another table called "Publisher". This table contains users who are allowed to contribute to the website via an administration console. All users in the Publisher table are also in the Individual table, but not all users in the Individual table are in the Publisher table.

Source Tables

Individual Table

IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike

Publisher Table

IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor

Our task is to return a list of usernames from all publishers who have an access level of "Contributor".

You may notice that the usernames are in the Individual table but the access level is stored in the Publisher table. Also, there could potentially be many contributors. This is a good candidate for the SQL IN operator!

SQL statement

SELECT UserName FROM Individual
WHERE IndividualId IN
(SELECT IndividualId
FROM Publisher
WHERE AccessLevel = 'Contributor')

Result

UserName
homey
notsofamous
sabbath

In this example there aren't many records in the Publisher table, but imagine if there were thousands - the IN statement is great for this sort of thing.

Enjoy this website?

  1. Link to this page (copy/paste into your own website or blog):
  2. Add this page to your favorite social bookmarks sites:
               
  3. Add this page to your Favorites

Oh, and thank you for supporting Quackit!