SQL Where

The WHERE clause filters the rows returned by a query so that only records meeting a condition are included.

What the WHERE clause does

Most tables hold far more data than you need for any single question. The WHERE clause lets you narrow a result set down to just the rows that satisfy a condition you describe. When SQL evaluates a query, it looks at each row, tests it against the condition, and keeps only the rows where the condition is true. Rows that do not match are quietly left out of the result.

Basic WHERE syntax

SELECT CustomerName, City, Country
FROM Customers
WHERE Country = 'Germany';

In the query above, only customers whose Country column holds the text 'Germany' are returned. Notice that the text value is wrapped in single quotes. In standard SQL, text (string) values are always enclosed in single quotes, while numeric values are written on their own without quotes.

Comparing a numeric column

SELECT CustomerName, CustomerID
FROM Customers
WHERE CustomerID = 42;
Note: Quoting a number, such as WHERE CustomerID = '42', often still works because many databases convert the value automatically, but it is clearer and usually faster to leave numeric literals unquoted.

Comparison operators you can use

The WHERE clause is not limited to checking for an exact match. You can compare values in several ways using the operators below. Each operator returns true or false for every row, and the row is kept only when the result is true.

OperatorMeaningExample
=Equal toWHERE Country = 'Spain'
<>Not equal to (also written as !=)WHERE Country <> 'Spain'
>Greater thanWHERE Price > 30
<Less thanWHERE Price < 30
>=Greater than or equal toWHERE Price >= 30
<=Less than or equal toWHERE Price <= 30

Filtering on a range with an operator

SELECT ProductName, Price
FROM Products
WHERE Price >= 50;
  • The condition after WHERE can reference any column in the table, even columns you are not selecting.
  • String comparisons are case-sensitive or case-insensitive depending on your database's collation settings.
  • You can combine several conditions in one WHERE clause using AND, OR, and NOT, which are covered in a later lesson.
  • WHERE also works with UPDATE and DELETE statements to control exactly which rows are changed or removed.
Note: When you run an UPDATE or DELETE statement, always double-check the WHERE clause first. A missing or incorrect condition can change or erase every row in the table.

Exercise: SQL Where

What is the purpose of the WHERE clause?