MySQL

WHERE Clause


The WHERE clause in SQL is used to filter records that meet a specified condition. It allows you to limit the result set to only those rows that match the given criteria. You can use operators such as =, >, <, LIKE, IN, BETWEEN, and more to filter data effectively.

 

 

Basic Syntax

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

 

 

1. Filtering by Equality (=)

Retrieve records that match a specific value.

Example:

SELECT * FROM Employees WHERE DepartmentID = 101;

This query retrieves all employees who are in department 101.

 

 

2. Filtering by Greater Than (>) or Less Than (<)

Filter records where values are greater than or less than a certain value.

Example:

SELECT * FROM Employees WHERE Salary > 50000;

This query retrieves all employees with a salary greater than 50,000.

 

 

3. Using AND and OR to Combine Conditions

You can combine multiple conditions using the AND and OR operators.

Example (Using AND):

SELECT * FROM Employees WHERE DepartmentID = 101 AND Salary > 50000;

This query retrieves employees in department 101 who also have a salary greater than 50,000.

Example (Using OR):

SELECT * FROM Employees WHERE DepartmentID = 101 OR DepartmentID = 102;

This query retrieves all employees in either department 101 or 102.

 

 

4. Using IN to Match a List of Values

The IN operator allows you to specify multiple possible values for a column.

Example:

SELECT * FROM Employees WHERE DepartmentID IN (101, 102, 103);

This query retrieves employees in departments 101, 102, or 103.

 

 

5. Using BETWEEN for Ranges

The BETWEEN operator is used to filter records within a specific range, inclusive of the range's boundaries.

Example:

SELECT * FROM Employees WHERE Salary BETWEEN 40000 AND 60000;
 
This query retrieves all employees with a salary between 40,000 and 60,000.