
MySQL IN
The MySQL IN operator is used to specify a list of values for matching against a specific column in a WHERE clause. It is often used to filter rows where a column’s value matches any of the specified values in the list. The IN operator simplifies queries that involve multiple OR conditions.
The basic syntax of the IN operator is as follows:
SELECT columns
FROM table
WHERE column_name IN (value1, value2, ...);
Here’s how it works:
column_nameis the name of the column you want to compare against.value1,value2, etc., are the values you want to match against.
Here are some examples to illustrate the use of the IN operator:
- Match all records where the
categoryis either “Electronics” or “Appliances”:
SELECT *
FROM products
WHERE category IN ('Electronics', 'Appliances');
- Match all records where the
customer_idis any of the specified values:
SELECT *
FROM orders
WHERE customer_id IN (101, 102, 103, 104);
- Match all records where the
stateis any of the specified U.S. states:
SELECT *
FROM customers
WHERE state IN ('NY', 'CA', 'TX', 'FL');
The IN operator provides a concise way to filter rows based on multiple values without having to use a series of OR conditions. It’s especially useful when you want to match against a predefined list of values.
Keep in mind that the list of values enclosed in parentheses after the IN operator can be a static list of values, or it can be a subquery that retrieves a list of values dynamically based on some other condition. This makes the IN operator a versatile tool for filtering and retrieving data from the database.