SQL IN Operator
The IN operator in SQL allows you to filter rows where a column's value matches any value in a list. It is often used as a shorthand for multiple OR conditions.
📌 Syntax
SELECT column1, column2, ... FROM table_name WHERE column_name IN (value1, value2, ...);
📊 Example Table: users
id | name | age | city ---+---------+-----+--------- 1 | Alice | 22 | New York 2 | Bob | 30 | London 3 | Charlie | 18 | Sydney 4 | Diana | 27 | Toronto 5 | Ethan | 35 | Paris
🔍 Example 1: Filter by Cities
Find users who live in London or Paris:
SELECT * FROM users WHERE city IN ('London', 'Paris');🔍 Example 2: Using IN with Numbers
Find users with ages 22, 27, or 30:
SELECT * FROM users WHERE age IN (22, 27, 30);
🔍 Example 3: NOT IN
Find users who are NOT in London or Paris:
SELECT * FROM users WHERE city NOT IN ('London', 'Paris');⚡ Best Practices
- Use
INinstead of multipleORfor cleaner queries. - Ensure the list of values is not too large; consider using a subquery for dynamic lists.
- Combine with
NOT INto exclude specific sets of values. - Use indexes on the column for faster lookups when working with large tables.
📝 Summary
The IN operator is a convenient way to filter rows based on multiple possible values in a column. It improves readability and reduces complex OR statements, making queries simpler and easier to maintain.
🚀 Next Steps
Next, we will explore the BETWEEN Operator, which allows filtering rows within a specific range of values.