Examples of IN Operator
Example 1: Filtering Products by CategoryID using IN Clause
Suppose we have a table named Products with columns ProductID, ProductName, and CategoryID. We want to retrieve all products belonging to either the ‘Electronics‘ or ‘Accessories‘ category.
SELECT *
FROM Products
WHERE CategoryID IN (1, 2);
Output:
Explanation: The output displays all products whose CategoryID is either 1 or 2 from the “same ” table.
Example 2: Filtering Orders by ProductID
Consider a scenario where we have a table named Orders with columns OrderID, ProductID, and Quantity. We need to fetch all orders containing either laptops or monitors.
SELECT *
FROM Orders
WHERE ProductID IN (1, 4);
Output:
Explanation: The output shows all orders containing products with ProductID 1 or 4 from the “Orders” table.
Difference Between EXISTS and IN in SQL Server?
The SQL Server database developer is quite familiar with the filtering and retrieving operators which enable the developer to execute the query rapidly. When it comes to these operators namely IN and EXISTS, they share almost similar purposes but work differently at the same level.
Understanding the variations between the two operators is very important for better tuning of query performance and the desired outcomes.