In this guide, we will explain how to use the MySQL WHERE clause with syntax and examples.
Description
The MySQL WHERE clause is used to filter the results from a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
The syntax for the WHERE Clause in MySQL is:
WHERE conditions;
Parameters or Arguments
conditionsThe conditions that must be met for records to be selected.
Example – With Single condition
It is difficult to explain the syntax for the MySQL WHERE clause, so let’s look at some examples.
SELECT * FROM contacts WHERE last_name = 'Johnson';
In this MySQL WHERE clause example, we’ve used the WHERE clause to filter our results from the contacts table. The SELECT statement above would return all rows from the contacts table where the last_name is Johnson. Because the * is used in the SELECT, all fields from the contacts table would appear in the result set.
Example – Using AND condition
SELECT * FROM suppliers WHERE state = 'Florida' AND supplier_id > 1000;
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions. In this case, this SELECT statement uses the AND Condition to return all suppliers that are located in the state of Florida and whose supplier_id is greater than 1000.
Example – Using OR condition
SELECT supplier_id FROM suppliers WHERE supplier_name = 'Apple' OR supplier_name = 'Microsoft';
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions, but instead of using the AND Condition, it uses the OR Condition. In this case, this SELECT statement would return all supplier_id values where the supplier_name is Apple or Microsoft.
Example – Combining AND & OR conditions
SELECT * FROM suppliers WHERE (state = 'Florida' AND supplier_name = 'IBM') OR (supplier_id > 5000);
This MySQL WHERE clause example uses the WHERE clause to define multiple conditions, but it combines the AND Condition and the OR Condition. This example would return all suppliers that reside in the state of Florida and whose supplier_name is IBM as well as all suppliers whose supplier_id is greater than 5000.
The parentheses determine the order that the AND and OR conditions are evaluated. Just like you learned in the order of operations in Math class!
Example – Joining Tables
SELECT suppliers.suppler_name, orders.order_id FROM suppliers, orders WHERE suppliers.supplier_id = orders.supplier_id AND suppliers.state = 'California';
This WHERE clause example uses the WHERE clause to join multiple tables together in a single SELECT statement. This SELECT statement would return all supplier_name and order_id values where there is a matching record in the suppliers and orders tables based on supplier_id, and where the supplier’s state is California.
Learn More : Click Here
Pingback: MySQL: UPDATE Statement | Adglob Infosystem Pvt Ltd
Pingback: MySQL: INTERSECT Operator | Adglob Infosystem Pvt Ltd
Pingback: MySQL: LIKE Condition | Adglob Infosystem Pvt Ltd