Quantcast
Channel: TechBrij
Viewing all articles
Browse latest Browse all 116

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

$
0
0


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

OrderID ProductID
1 1
1 2
1 3
2 1
2 3
3 2
3 3
4 3
5 2
5 4

——————————–

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.

Related posts:

  1. Implement Audit Trail Quickly for Microsoft SQL Server
  2. Grouping Data in ASP.NET Gridview Control
  3. Run Your Custom Script Quickly with SSMS Tools Pack
  4. Install sql server database with visual studio setup
  5. Concurrency violation: the UpdateCommand affected 0 of the expected 1 records

Viewing all articles
Browse latest Browse all 116

Trending Articles