Filtering a list with IN #
Checking a column against several possible values with OR gets repetitive fast. The IN keyword lets you list all the values you want to match in one place.
Syntax #
SELECT
column_name
FROM
table_name
WHERE
column_name IN (value_1, value_2, value_3);
A row matches if column_name equals any of the values in the list.
Example #
SELECT
*
FROM
products
WHERE
category IN ('Electronics', 'Fitness');
is equivalent to:
SELECT
*
FROM
products
WHERE
category = 'Electronics'
OR category = 'Fitness';
Result:
+----+-------------------+-------------+-------+
| id | name | category | price |
+----+-------------------+-------------+-------+
| 1 | Wireless Mouse | Electronics | 19.99 |
| 2 | Bluetooth Speaker | Electronics | 45.5 |
| 3 | Yoga Mat | Fitness | 25.0 |
| 4 | Running Shoes | Fitness | 60.0 |
+----+-------------------+-------------+-------+
Products from the Home and Office categories are excluded, since neither category appears in the list.
Exercise #
Write a query that retrieves all columns from the products table, keeping only the rows where category is 'Electronics' or 'Fitness'.
- The result has a
categorycolumn. - The result contains exactly the rows where
categoryis'Electronics'or'Fitness', and no others.
Solution
SELECT
*
FROM
products
WHERE
category IN ('Electronics', 'Fitness');
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity