SQL IN Keyword
The IN
operator in SQL allows you to check if a value matches any value within a list of values. It's a concise way to express multiple OR
conditions.
IN: Definition and Usage
Instead of writing many OR
conditions, you can use IN
to simplify your WHERE
clause. IN
checks if a column value is present within a set of specified values. It's often more readable and efficient than writing multiple OR
conditions.
Syntax
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name IN (value1, value2, value3, ...);
--To exclude values from the list:
SELECT column1, column2, ...
FROM table_name
WHERE column_name NOT IN (value1, value2, value3, ...);
Examples
Selecting Customers from Specific Countries
This query retrieves all customers located in Germany, France, or the UK.
Syntax
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Output
(All rows from the Customers table where Country is 'Germany', 'France', or 'UK' will be returned.)
Selecting Customers NOT from Specific Countries
This query retrieves customers who are *not* located in Germany, France, or the UK.
Syntax
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
Output
(All rows from the Customers table where Country is NOT 'Germany', 'France', or 'UK' will be returned.)
Selecting Customers from Countries Matching Suppliers
This query uses a subquery to find customers from countries where suppliers are also located. (Assumes the existence of a 'Suppliers' table with a 'Country' column).
Syntax
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
Output
(All rows from the Customers table where the Country matches any Country in the Suppliers table will be returned.)