
When working with databases, filtering data is one of the main tasks. In MySQL, the WHERE clause is your primary tool for doing this. This guide breaks down the concept of the WHERE clause with several examples to better explain this command.
Understanding the WHERE Clause
The WHERE clause in MySQL is used to filter records based on specified conditions. It’s used in conjunction with SQL statements like SELECT, UPDATE, or DELETE to manipulate data more precisely.
Basic Syntax
The basic structure of a WHERE clause is:
The condition specifies which rows should be retrieved, updated, or deleted.
1. Simple Conditions
Example: Equality
To select users with the name 'John Doe':
Example: Inequality
To select products with a price greater than 100:
2. Combining Conditions
You can use AND, OR, and NOT to combine multiple conditions.
Example: Using AND
To find users named 'John Doe' who are 30 years old:
Example: Using OR
To select users who are either 25 or 30 years old:
Example: Using NOT
To select all users except those named 'John Doe':
3. Using Comparison Operators
MySQL supports various comparison operators such as =, !=, <, >, <=, >=.
Example: Less Than
To find products with a stock quantity less than 50:
4. LIKE Operator
The LIKE operator is used for pattern matching.
Example: Using LIKE
To find users with names starting with 'J':
% is a wildcard character representing any number of characters.
5. BETWEEN Operator
BETWEEN selects values within a given range.
Example: Using BETWEEN
To select products with a price range between 50 and 100:
6. IN Operator
IN allows you to specify multiple values in a WHERE clause.
Example: Using IN
To select users who are either 25, 30, or 35 years old:
7. Working with NULL
IS NULL and IS NOT NULL check for NULL values.
Example: Finding NULL
To find products without a specified category: