
MySQL WHERE
The MySQL WHERE
clause is used to filter rows in a query based on a specified condition or set of conditions. The WHERE
clause is often used in conjunction with the SELECT
statement to retrieve data that meets certain criteria. It is also used in other SQL statements, such as UPDATE
, DELETE
, and INSERT INTO ... SELECT
.
The basic syntax of the WHERE
clause is as follows:
SELECT columns
FROM table
WHERE condition;
Here’s how it works:
columns
are the columns you want to retrieve from the table.table
is the name of the table you want to query.condition
is the expression that specifies the filtering criteria. Rows that meet the condition are included in the result set.
Here are some examples of how to use the WHERE
clause in MySQL:
- Retrieve all columns from the
employees
table for employees who work in the “Sales” department:
SELECT *
FROM employees
WHERE department = 'Sales';
- Retrieve the names and prices of products with a price greater than $100:
SELECT product_name, price
FROM products
WHERE price > 100;
- Update the
discount
column for products with a price greater than $500:
UPDATE products
SET discount = 0.10
WHERE price > 500;
- Delete all records from the
orders
table with anorder_date
earlier than a specific date:
DELETE FROM orders
WHERE order_date < '2023-01-01';
The WHERE
clause allows you to filter and manipulate data based on specific conditions, making it a fundamental part of SQL queries and operations. It is used to extract, update, or delete data based on the criteria you specify, which helps you work with the data in a more precise and targeted way.