π SQL IN Operator β Match Multiple Values with Clean Code
Want to match a column against multiple values without repeating
ORconditions?
The SQLINoperator is your go-to solution for elegant filtering and clean queries.
π What is SQL IN?
The SQL IN operator allows you to specify multiple values in a WHERE clause. It returns rows where the column value matches any value in the list.
π‘ Itβs a shorter, more readable alternative to multiple OR conditions.
π§Ύ SQL IN Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, value3, ...);
β
Returns all rows where column_name equals any of the values listed.
β Example: Filter by City
SELECT customer_name, city
FROM customers
WHERE city IN ('Mumbai', 'Delhi', 'Bangalore');
π Returns customers located in Mumbai, Delhi, or Bangalore.
π« NOT IN Operator
To exclude specific values, use NOT IN:
SELECT employee_name, department
FROM employees
WHERE department NOT IN ('HR', 'Finance');
π This returns employees who are not in HR or Finance.
π§ Use IN with Numbers
SELECT product_name, price
FROM products
WHERE price IN (999, 1499, 1999);
π Selects products with specific price points.
π
Use IN with Dates
SELECT order_id, order_date
FROM orders
WHERE order_date IN ('2024-01-01', '2024-05-01', '2024-08-15');
π― Filters orders placed on specific dates.
π IN vs Multiple OR Conditions
-- Using OR
SELECT * FROM users
WHERE role = 'Admin' OR role = 'Editor' OR role = 'Viewer';
-- Cleaner with IN
SELECT * FROM users
WHERE role IN ('Admin', 'Editor', 'Viewer');
β
The IN version is shorter, more readable, and easier to maintain.
β οΈ Best Practices & Tips
- Use
INonly when the list size is reasonable (e.g., < 1000 items). - Avoid using
NOT INwithNULLvaluesβuseNOT EXISTSorLEFT JOINinstead. - Combine with
AND,BETWEEN, orLIKEfor powerful filters.
π§ͺ Practice Challenge
Task: Retrieve products that are available in either ‘Red’, ‘Blue’, or ‘Black’ color.
SELECT product_name, color
FROM products
WHERE color IN ('Red', 'Blue', 'Black');
π Final Thoughts
The SQL IN operator is:
β
Shorter than using multiple OR conditions
β
Easier to read and maintain
β
Perfect for filtering by lists of values in real-world datasets
Start using IN in your queries to make them cleaner, faster, and easier to debug.