Menu

SQL

The WHERE Clause

The WHERE clause gives a condition that a record must meet to be included in a query result. Records that meet the condition are returned; records that do not meet it are left out.

WHERE is optional. If you leave it out, no records are filtered, so every record in the table is returned. Add WHERE only when you want to narrow the result.

Conditions use these comparison operators:

OperatorMeaning
=equal to
>greater than
<less than
>=greater than or equal to
<=less than or equal to
<>not equal to

In SQL, equality uses a single equals sign, =. A double equals sign, ==, is not used in an SQL condition, even though it may be used for comparison in program code.

A condition can include the boundary value itself. For example, a query asking for seedlings at least 30 cm tall uses >= with 30, so a seedling exactly 30 cm tall is included as well as taller ones. Using > instead would leave out that 30 cm seedling while still returning the taller ones.

The wording of a request tells you which operator to use: under or less than uses <, over or more than uses >, and at least, or a phrase such as 5 or more, uses >=.

Text values must be enclosed in quotation marks, for example Subject = "Art". Numbers are written without quotation marks, for example Copies > 5. The quotation marks show that the value is text; adding them around a number is unnecessary.

The SQL keyword is WHERE, not IF. IF belongs in program code, not in an SQL query.

Practise this