The SQL IN operator is used to filter data by specifying a set of values. It is a shorthand for using multiple OR conditions. The IN operator checks whether a given value exists within a specified list of values.
Syntax:
Key Points:
- The values in the
INclause can be numbers, strings, or subqueries. - It is case-sensitive in most databases when comparing strings (depending on the collation settings).
- It simplifies queries compared to using multiple
ORconditions.
Example 1: Using IN with a List of Values
This query retrieves all employees who belong to departments 1, 3, or 5.
Example 2: Using IN with a Subquery
This query retrieves all employees whose departments are located in New York.
Example 3: Using NOT IN
You can use the NOT IN operator to exclude specific values:
This query retrieves all employees who are not in departments 2, 4, or 6.
Benefits of IN:
- Cleaner and more readable syntax for multiple comparisons.
- Reduces the complexity of queries compared to using
OR.
No comments:
Post a Comment