Introduction to the WHERE Clause

The WHERE clause in MySQL is a fundamental part of writing SQL queries. It allows you to filter and retrieve specific rows from a table based on specified conditions. In this guide, we'll explore how to combine conditions in the WHERE clause to create complex queries for precise data retrieval.


Basic Syntax of the WHERE Clause

The basic syntax of the WHERE clause in a MySQL query is as follows:

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND/OR condition2;

You can use logical operators such as

AND
and
OR
to combine multiple conditions.


Combining Conditions with AND

When using the

AND
operator in the WHERE clause, both conditions must be true for a row to be included in the result set. For example:

SELECT product_name, price
FROM products
WHERE category = 'Electronics' AND price < 500;

This query retrieves products in the "Electronics" category with a price less than $500.


Combining Conditions with OR

When using the

OR
operator in the WHERE clause, at least one of the conditions must be true for a row to be included in the result set. For example:

SELECT product_name, price
FROM products
WHERE category = 'Clothing' OR category = 'Shoes';

This query retrieves products in either the "Clothing" or "Shoes" category.


Combining Conditions with Parentheses

You can use parentheses to group conditions and control the order of evaluation. This is useful for creating complex queries. For example:

SELECT product_name, price
FROM products
WHERE (category = 'Electronics' AND price < 500) OR (category = 'Clothing' AND price > 50);

This query retrieves products that are either in the "Electronics" category with a price less than $500 or in the "Clothing" category with a price greater than $50.


Conclusion

The MySQL WHERE clause is a powerful tool for filtering and retrieving specific data from your database. By combining conditions using logical operators and parentheses, you can create complex queries to meet your specific data retrieval needs.