SQL WHERE Keyword
Introduction
The WHERE keyword is fundamental in SQL. It allows you to filter the results of a query, showing only the rows (records) that meet a specific condition. This makes your queries more precise and efficient.
Basic Usage
The WHERE clause is used with the SELECT statement (and others like UPDATE and DELETE) to filter data.
Example 1: Filtering Text Data
This example selects all customers from Mexico from a "Customers" table.
SQL Query
SELECT * FROM Customers WHERE Country='Mexico';
Output
(This output will show all columns (*) for customers where the Country column is 'Mexico'. The specific data depends on your 'Customers' table.)
Example 2: Filtering Numeric Data
This example selects a specific customer using their numeric CustomerID.
SQL Query
SELECT * FROM Customers WHERE CustomerID=1;
Output
(This will display all columns (*) for the customer with CustomerID 1. The data will depend on your 'Customers' table.)
Important Notes
- SQL uses single quotes around text values (although some database systems might allow double quotes).
- Numeric fields should not be enclosed in quotes.
- The
WHEREclause isn't limited toSELECTstatements; it's also used withUPDATE,DELETE, and other SQL commands.
Comparison Operators
The WHERE clause uses comparison operators to define the conditions:
| Operator | Description |
|---|---|
= |
Equal to |
<> or != |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
BETWEEN |
Within a specified range |
LIKE |
Used for pattern matching (e.g., finding names starting with 'A') |
IN |
Specifies multiple possible values for a column (e.g., selecting customers from 'USA', 'Canada', or 'Mexico') |