Feb 26, 2012

How To Use SQL IN Statement to Select Data Having All Specified Values

Generally, We use SQL Where .. IN Statement to determine whether a specified value matches ANY value in a sub-query or a list. But sometimes we require to get data which have ALL specified values, not ANY value. In this post, we'll see how to accomplish it. Let's take an example, Consider following data in Orders table

OrderIDProductID
11
12
13
21
23
32
33
43
52
54

--------------------------------

SQL Query:

Select distinct OrderID

From Orders

Where ProductID in (2,3)

--------------------------------

The above query selects OrderIDs which has any specified ProductID (2 or 3 or both)

Output:

1

2

3

4

5

Now, we want to select OrderIDs which have ALL specified values (2 and 3 both). See following SQL query:

--------------------------------

Select OrderID

From Orders

Where ProductID in (2,3)

group by OrderID

having count(*) = 2

--------------------------------

Output:

1

3

Which is expected. In above query, We are grouping by OrderID, counting and select if count is equal to total number of items in the specified values. If there are 5 items in IN condition then you have to set having count(*) = 5.

Hope, It saves your time. Let me know how you are doing to do this.