π― SQL IN Operator β Use IN and NOT IN for Multi-Value Filters
π§² Introduction β What is SQL IN?
The IN
operator in SQL is used to match a columnβs value against a list of values. It makes multiple OR conditions concise, readable, and efficient.
π― In this guide, youβll learn:
- Basic syntax of
IN
andNOT IN
- Use with numbers, strings, and subqueries
- Best practices and common pitfalls
β 1. Basic SQL IN Syntax
SELECT * FROM employees
WHERE department IN ('HR', 'IT', 'Finance');
β
Returns rows where department
is one of the listed values.
π 2. Using NOT IN
SELECT * FROM products
WHERE category NOT IN ('Discontinued', 'Obsolete');
β Excludes rows matching any value in the list.
π§ 3. IN vs Multiple ORs
-- Using OR
WHERE department = 'HR' OR department = 'IT' OR department = 'Finance';
-- Using IN
WHERE department IN ('HR', 'IT', 'Finance');
β
IN
is cleaner and performs better on large sets.
π 4. IN with Numeric Values
SELECT * FROM orders
WHERE status_code IN (200, 201, 404);
β Works with integers and decimals too.
π 5. IN with Subqueries
SELECT * FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE active = true);
β Dynamically filters based on another tableβs values.
β οΈ 6. Caution with NULLs in NOT IN
-- This may return 0 rows if the list contains NULL
WHERE status NOT IN ('active', NULL);
β
Always filter NULLs out in subqueries when using NOT IN
.
π Best Practices
β Recommended | β Avoid This |
---|---|
Use IN for multi-value filters | Writing long OR conditions |
Filter out NULLs when using NOT IN | Ignoring NULLs in subquery lists |
Use subqueries for dynamic filtering | Hardcoding long lists unnecessarily |
π Summary β Recap & Next Steps
The IN
operator allows for cleaner, more maintainable filtering when working with multiple values. Itβs ideal for status checks, lookups, and relationship-based queries.
π Key Takeaways:
- Use
IN
for simple multi-value matches - Use
NOT IN
to exclude specific values - Subqueries let you create dynamic IN lists
- Avoid NULLs with
NOT IN
for safe logic
βοΈ Real-World Relevance:
Used in filters, dropdown selections, security rules, and conditional logic for audit trails.
β‘οΈ Next: Explore BETWEEN
for filtering within numeric and date ranges.
β FAQ β SQL IN Operator
β What does SQL IN do?
β Filters rows where a column matches one of the values in a list.
β Can I use IN with numbers and strings?
β Yes. The values inside the list must match the columnβs data type.
β Is IN better than multiple OR conditions?
β Itβs shorter, easier to read, and often performs better.
β Can I use IN with a subquery?
β Yes, and it’s highly useful for dynamic conditions.
β What should I watch out for with NOT IN?
β
NULLs in the list may cause unexpected behavior. Use WHERE ... IS NOT NULL
to clean subquery results.
Share Now :