Complete MySQL WHERE Clause guide with examples

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:

SQL
SELECT column1, column2, ...
FROM table_name
WHERE condition;

The condition specifies which rows should be retrieved, updated, or deleted.

1. Simple Conditions

Example: Equality

To select users with the name 'John Doe':

SQL
SELECT * FROM Users
WHERE Name = 'John Doe';

Example: Inequality

To select products with a price greater than 100:

SQL
SELECT * FROM Products
WHERE Price > 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:

SQL
SELECT * FROM Users
WHERE Name = 'John Doe' AND Age = 30;

Example: Using OR

To select users who are either 25 or 30 years old:

SQL
SELECT * FROM Users
WHERE Age = 25 OR Age = 30;

Example: Using NOT

To select all users except those named 'John Doe':

SQL
SELECT * FROM Users
WHERE NOT Name = '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:

SQL
SELECT * FROM Products
WHERE Stock < 50;

4. LIKE Operator

The LIKE operator is used for pattern matching.

Example: Using LIKE

To find users with names starting with 'J':

SQL
SELECT * FROM Users
WHERE Name LIKE '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:

SQL
SELECT * FROM Products
WHERE Price 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:

SQL
SELECT * FROM Users
WHERE Age IN (25, 30, 35);

7. Working with NULL

IS NULL and IS NOT NULL check for NULL values.

Example: Finding NULL

To find products without a specified category:

SQL
SELECT * FROM Products
WHERE Category IS NULL;