The WHERE clause is used to specify a selection criteria.
To conditionally select data from a table, a WHERE clause can be added to the SELECT statement with the following syntax:
SELECT column FROM table WHERE column condition value |
With the WHERE clause, these conditions can be used:
| Operator | Condition |
| = | Equal |
| <> | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| BETWEEN | Between an inclusive range |
| LIKE | Explained below |
Note: In some versions of SQL the not equal operator <> can be written as !=
To select only the people that live in Sandnes, add a WHERE clause to the SELECT statement like this:
SELECT * FROM Persons WHERE City='Sandnes' |
The "Persons" Table:
| LastName | FirstName | Address | City | Year |
|---|---|---|---|---|
| Hansen | Ola | Timoteivn 10 | Sandnes | 1951 |
| Svendson | Tove | Borgvn 23 | Sandnes | 1978 |
| Svendson | Ståle | Kaivn 18 | Sandnes | 1980 |
| Pettersen | Kari | Storgt 20 | Stavanger | 1960 |
The Result:
| LastName | FirstName | Address | City | Year |
|---|---|---|---|---|
| Hansen | Ola | Timoteivn 10 | Sandnes | 1951 |
| Svendson | Tove | Borgvn 23 | Sandnes | 1978 |
| Svendson | Ståle | Kaivn 18 | Sandnes | 1980 |
Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values. Most database systems will also accept double quotes. Numeric values should not be enclosed in quotes.
For Text values:
This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is not correct: SELECT * FROM Persons WHERE FirstName=Tove |
For Numeric values:
This is correct: SELECT * FROM Persons WHERE Year>1965 This is not correct: SELECT * FROM Persons WHERE Year>'1965' |
The LIKE condition is used to specify a search for a pattern in a column.
The syntax is like this:
SELECT column FROM table WHERE column LIKE pattern |
A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
This SQL statement will return persons with a first name that start with an 'O'.
SELECT * FROM Persons WHERE FirstName LIKE 'O%' |
This SQL statement will return persons with a first name that end with an 'a'.
SELECT * FROM Persons WHERE FirstName LIKE '%a' |
This SQL statement will return persons with a first name that contains the pattern 'la'.
SELECT * FROM Persons WHERE FirstName LIKE '%la%' |
All the examples above will return the following result:
| LastName | FirstName | Address | City | Year |
|---|---|---|---|---|
| Hansen | Ola | Timoteivn 10 | Sandnes | 1951 |