SQL In

The IN operator in SQL allows you to specify multiple values in a WHERE clause. It is used to filter records based on a list of values, making queries more readable and efficient.

Syntax

The basic syntax of the IN operator is:


SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, ...);

        

Examples

Here are some examples of using the IN operator:


-- Select all employees who work in either 'Sales' or 'Marketing'
SELECT * FROM Employees
WHERE Department IN ('Sales', 'Marketing');

-- Select all products with IDs 1, 3, or 5
SELECT * FROM Products
WHERE ProductID IN (1, 3, 5);

-- Select all orders with status 'Pending' or 'Shipped'
SELECT * FROM Orders
WHERE Status IN ('Pending', 'Shipped');

        

Using Subqueries

The IN operator can also be used with subqueries. This allows you to filter results based on the results of another query:


-- Select all employees who work in departments located in 'New York'
SELECT * FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE Location = 'New York');