WHERE Clause
This SQL tutorial explains how to use the SQL WHERE clause with syntax and examples.
Description
The SQL WHERE clause is used to filter the results and apply conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
Syntax
The syntax for the SQL WHERE Clause is:
WHERE conditions;
Parameters or Arguments
conditions
The conditions that must be met for records to be selected.
Example - With Single condition
It is difficult to explain the syntax for the SQL WHERE clause, so let's look at some examples.
SELECT *
FROM suppliers
WHERE supplier_name = 'IBM';
In this SQL WHERE clause example, we've used the SQL WHERE clause to filter our results from the suppliers table. The SQL statement above would return all rows from the suppliers table where the supplier_name is IBM. Because the * is used in the select, all fields from the suppliers table would appear in the result set.
Example - Using AND condition
SELECT *
FROM suppliers
WHERE supplier_city = 'Chicago'
AND supplier_id > 1000;
This SQL WHERE clause example uses the WHERE clause to define multiple conditions. In this case, this SQL statement uses the AND Condition to return all suppliers that are located in Chicago and whose supplier_id is greater than 1000.
Example - Using OR condition
SELECT supplier_id
FROM suppliers
WHERE supplier_name = 'IBM'
OR supplier_name = 'Apple';
This SQL 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 SQL statement would return all supplier_id values where the supplier_name is IBM or Apple.
Example - Combining AND & OR conditions
SELECT *
FROM suppliers
WHERE (city = 'New York' AND name = 'IBM')
OR (ranking >= 10);
This SQL 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 New York whose name is IBM and all suppliers whose ranking is greater than or equal to 10.
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
INNER JOIN orders
ON suppliers.supplier_id = orders.supplier_id
WHERE suppliers.supplier_city = 'Atlantic City';
This SQL WHERE clause example uses the SQL WHERE clause to join multiple tables together in a single SQL statement. This SQL statement would return all supplier names and order_ids where there is a matching record in the suppliers and orders tables based on supplier_id, and where the supplier_city is Atlantic City.