SQL WHERE Clause

The WHERE clause in SQL is used to filter records from a table based on specified conditions. It allows you to select only the rows that meet certain criteria, making your queries more precise and efficient.



WHERE Clause: Definition and Usage

The WHERE clause comes after the FROM clause in a SELECT statement (and can be used with other SQL statements like UPDATE and DELETE). It lets you specify conditions that must be met for a row to be included in the result set. This dramatically reduces the amount of data returned, making queries faster and easier to manage.

Syntax

Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;
      

Example Database: Customers Table

Let's use this sample 'Customers' table for the following examples:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

Examples Using WHERE

Selecting Customers from a Specific Country

This query retrieves all customers from Mexico.

Syntax

SELECT * FROM Customers
WHERE Country = 'Mexico';
      
Output

(Only Customers where Country is 'Mexico' will be returned)
      

Data Types and Quotes

Remember to enclose text values in single quotes, but not numeric values.

Syntax

SELECT * FROM Customers
WHERE CustomerID = 1;
      
Output

(Only the customer with CustomerID 1 will be returned)
      

Using Comparison Operators

This query retrieves customers with a CustomerID greater than 80.

Syntax

SELECT * FROM Customers
WHERE CustomerID > 80;
      
Output

(Customers with CustomerID greater than 80 will be returned)
      

Available Operators in WHERE Clause

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= or <> Not equal to
BETWEEN Within a range
LIKE Pattern matching
IN Matches any value in a list

**Note:** The example outputs assume a `Customers` table exists with the specified columns. The actual output will depend on the data within your `Customers` table. If no customers meet the specified criteria, the output will be an empty result set.