sql_in
SQL IN Operator
Section titled “SQL IN Operator”The IN Operator
Section titled “The IN Operator”The IN operator allows you to specify multiple values in a WHERE clause. It serves as a shorthand for multiple OR conditions, often making queries more readable and sometimes more performant.
SQL IN Syntax
Section titled “SQL IN Syntax”SELECT column_name(s)FROM table_nameWHERE column_name IN (value1, value2, ...);The IN operator can also be used with a subquery that returns a single column of values:
SELECT column_name(s)FROM table_nameWHERE column_name IN (SELECT another_column FROM another_table WHERE condition);You can also use NOT IN to exclude rows that match any value in the list.
Demo Database: Northwind
Section titled “Demo Database: Northwind”We’ll use the “Customers” table from the Northwind sample database.
CustomerID | CustomerName | City | Country-----------|-----------------------------------|------------|---------1 | Alfreds Futterkiste | Berlin | Germany2 | Ana Trujillo Emparedados y helados| México D.F.| Mexico3 | Antonio Moreno Taquería | México D.F.| Mexico4 | Around the Horn | London | UK5 | Berglunds snabbköp | Luleå | Sweden...IN Operator Examples
Section titled “IN Operator Examples”Example 1: Selecting customers from specific cities
Section titled “Example 1: Selecting customers from specific cities”The following SQL statement selects all customers located in ‘Paris’ or ‘London’:
SELECT *FROM CustomersWHERE City IN ('Paris', 'London');This is equivalent to:
SELECT *FROM CustomersWHERE City = 'Paris' OR City = 'London';Example 2: Using IN with a Subquery
Section titled “Example 2: Using IN with a Subquery”Suppose you want to find all customers who have placed orders. (Note: An INNER JOIN is often a more direct way to do this, but this illustrates IN with a subquery).
SELECT CustomerName, City, CountryFROM CustomersWHERE CustomerID IN (SELECT DISTINCT CustomerID FROM Orders);Practical Application:
The IN operator is very useful when:
- Filtering by a fixed set of known values (e.g., product IDs, status codes, specific regions).
- Filtering based on results from another query (dynamic criteria).
- Improving query readability compared to long chains of
ORconditions.
Considerations:
Section titled “Considerations:”- Performance: For very long lists of literal values, performance might vary by database system. Some systems optimize
INwell, while others might struggle with extremely large lists. UsingINwith a subquery is generally well-optimized. NULLvalues: Be cautious whenNULLvalues are present in the list or the column being compared.column_name IN (value1, NULL, value2)will behave differently from what might be expected regardingNULLcomparisons. Typically,NULLdoes not equalNULLandNULLdoes not equal any other value.