Wednesday, January 9, 2013

WHERE Clause


The SQL WHERE clause allows you to filter the results from an SQL statement - SQL SELECT statement, SQL INSERT statement, SQL UPDATE statement, or SQL DELETE statement.
It is difficult to explain the syntax for the SQL WHERE clause, so instead, we'll take a look at some examples.

SQL WHERE Clause - Single condition example

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.

SQL WHERE Clause - Using SQL "AND" condition example

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 SQL "AND" Condition to return all suppliers that are located in Chicago and whose supplier_id is greater than 1000.

SQL WHERE Clause - Using SQL "OR" condition example

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 SQL "AND" Condition, it uses the SQL "OR" Condition. In this case, this SQL statement would return all supplier_id values where the supplier_name is IBM or Apple.

SQL WHERE Clause - Joining Tables example

SELECT suppliers.suppler_name, orders.order_id
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and 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.
Learn more about SQL joins.