MySQL WHERE Clause
Introduction
The WHERE
clause is one of the most important components of MySQL queries. It allows you to filter data by specifying conditions that must be met for records to be included in the query results. Without filtering, your queries would return all records in a table, which is rarely what you want in real applications.
In this tutorial, you'll learn how to use the WHERE
clause to specify conditions, filter data, and retrieve only the information you need from your database tables.
Basic Syntax
The basic syntax of a WHERE
clause in MySQL is:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The WHERE
clause appears after the FROM
clause in a SELECT
statement and before any GROUP BY
, HAVING
, or ORDER BY
clauses.
Simple Conditions
Let's start with some simple conditions using our example database. Assume we have a products
table with the following structure:
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
price DECIMAL(10, 2),
stock INT,
date_added DATE
);
Equality Comparison
To select products where the category is exactly "Electronics":
SELECT product_id, product_name, price
FROM products
WHERE category = 'Electronics';
Output:
+------------+-------------------+--------+
| product_id | product_name | price |
+------------+-------------------+--------+
| 1 | Smartphone X | 699.99 |
| 3 | Wireless Headset | 149.99 |
| 5 | Smart Watch | 249.99 |
+------------+-------------------+--------+
Inequality Comparison
To find products that are not in the "Clothing" category:
SELECT product_name, category
FROM products
WHERE category != 'Clothing';
You can also use the <>
operator instead of !=
:
SELECT product_name, category
FROM products
WHERE category <> 'Clothing';
Comparison Operators
MySQL supports the following comparison operators:
=
Equal to!=
or<>
Not equal to<
Less than>
Greater than<=
Less than or equal to>=
Greater than or equal to
Example: Find products priced higher than $200:
SELECT product_name, price
FROM products
WHERE price > 200;
Output:
+----------------+--------+
| product_name | price |
+----------------+--------+
| Smartphone X | 699.99 |
| Laptop Pro | 1299.99|
| Smart Watch | 249.99 |
+----------------+--------+
Combining Multiple Conditions
Logical AND
To combine multiple conditions where ALL conditions must be true, use the AND
operator:
SELECT product_name, price, stock
FROM products
WHERE price < 200 AND stock > 10;
This query returns products that cost less than $200 AND have more than 10 items in stock.
Logical OR
To combine conditions where AT LEAST ONE condition must be true, use the OR
operator:
SELECT product_name, category, price
FROM products
WHERE category = 'Electronics' OR price > 500;
This query returns products that are either in the Electronics category OR cost more than $500.
Logical NOT
The NOT
operator negates a condition:
SELECT product_name, category
FROM products
WHERE NOT category = 'Electronics';
This is equivalent to:
SELECT product_name, category
FROM products
WHERE category <> 'Electronics';
Combining AND, OR and NOT
You can combine these operators for complex conditions. Use parentheses to make the logic clear:
SELECT product_name, category, price, stock
FROM products
WHERE (category = 'Electronics' AND price < 300)
OR (stock < 5 AND NOT category = 'Clothing');
Special Conditions
BETWEEN Operator
The BETWEEN
operator selects values within a given range (inclusive):
SELECT product_name, price
FROM products
WHERE price BETWEEN 100 AND 300;
This returns products with prices from 300 (including both 300).
IN Operator
The IN
operator allows you to specify multiple values in a WHERE clause:
SELECT product_name, category
FROM products
WHERE category IN ('Electronics', 'Books', 'Games');
This returns products in any of the listed categories.
LIKE Operator
The LIKE
operator performs pattern matching:
SELECT product_name
FROM products
WHERE product_name LIKE 'Smart%';
This returns products whose names start with "Smart".
Pattern wildcards:
%
- Represents zero, one, or multiple characters_
- Represents exactly one character
Examples:
'%phone%'
- Contains "phone" anywhere'S_art'
- Starts with "S", then any single character, followed by "art"
IS NULL / IS NOT NULL
To find records with NULL values:
SELECT product_name, description
FROM products
WHERE description IS NULL;
To find non-NULL records:
SELECT product_name, description
FROM products
WHERE description IS NOT NULL;
Real-World Examples
E-commerce Filtering
Imagine you're building an e-commerce website and need to show products that are:
- In the Electronics category
- Priced under $500
- Currently in stock
SELECT product_name, price, stock
FROM products
WHERE category = 'Electronics'
AND price < 500
AND stock > 0
ORDER BY price;
Date Filtering
Find products added in the last 30 days:
SELECT product_name, date_added
FROM products
WHERE date_added >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);
Complex Business Rule
Find discountable products based on complex business rules:
SELECT product_name, price, category, stock
FROM products
WHERE (price > 100 AND stock > 20)
OR (category = 'Clearance' AND price > 50)
OR (date_added < DATE_SUB(CURRENT_DATE(), INTERVAL 180 DAY) AND stock > 10);
Subquery in WHERE Clause
You can also use subqueries in a WHERE clause:
SELECT product_name, price
FROM products
WHERE product_id IN (
SELECT product_id
FROM order_items
GROUP BY product_id
HAVING COUNT(*) > 10
);
This finds products that have appeared in more than 10 orders.
Common Mistakes and Tips
Case Sensitivity
By default, string comparisons in MySQL are not case-sensitive. If you need case-sensitive comparisons, you can use the BINARY
keyword:
SELECT product_name
FROM products
WHERE BINARY category = 'electronics'; -- Won't match 'Electronics'
Optimizing WHERE Clauses
For better performance:
- Place the most restrictive conditions first when using
AND
- Ensure columns used in WHERE clauses are indexed
- Avoid using functions on indexed columns in the WHERE clause, as this prevents index usage
Leading Wildcards
Using a leading wildcard (like LIKE '%phone'
) prevents the use of indexes and can be slow on large tables. Try to avoid if possible.
Summary
The WHERE
clause is an essential part of MySQL queries that allows you to filter data based on specific conditions. Key points to remember:
- Use comparison operators (
=
,<>
,<
,>
,<=
,>=
) for basic conditions - Combine conditions with logical operators (
AND
,OR
,NOT
) - Use special operators like
BETWEEN
,IN
, andLIKE
for more complex filtering - Handle
NULL
values withIS NULL
andIS NOT NULL
- Be aware of performance implications, especially with wildcards and functions
By mastering the WHERE
clause, you can retrieve exactly the data you need from your database, making your applications more efficient and responsive.
Practice Exercises
- Write a query to find all products in the 'Books' category with a price less than $20.
- Find all products that have the word 'Pro' in their name and cost more than $200.
- List products that are either out of stock OR were added more than 90 days ago.
- Find products that are not in the categories 'Electronics', 'Clothing', or 'Books'.
- Create a query to find products with stock between 5 and 15, and price above the average product price.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)