The WHERE clause is used to
specify a selection criterion.
To conditionally select data from
a table, a WHERE clause can be added to the SELECT statement.
SELECT column FROM tableWHERE column operator value |
With the WHERE clause, the following
operators can be used:
|
Operator |
Description |
|
= |
Equal |
|
<> |
Not equal |
|
> |
Greater than |
|
< |
Less than |
|
>= |
Greater than or equal |
|
<= |
Less than or equal |
|
BETWEEN |
Between an inclusive range |
|
LIKE |
Search for a pattern |
|
IN |
If you know the exact value you want to return for at least one
of the columns |
Note: In some versions of SQL the <>
operator may be written as !=
To select only the persons living
in the city "Sandnes", we add a WHERE clause to the SELECT
statement:
SELECT * FROM PersonsWHERE City='Sandnes' |
"Persons" table
|
LastName |
FirstName |
Address |
City |
Year |
|
Hansen |
Ola |
Timoteivn 10 |
Sandnes |
1951 |
|
Svendson |
Tove |
Borgvn 23 |
Sandnes |
1978 |
|
Svendson |
Stale |
Kaivn 18 |
Sandnes |
1980 |
|
Pettersen |
Kari |
Storgt 20 |
|
1960 |
Result
|
LastName |
FirstName |
Address |
City |
Year |
|
Hansen |
Ola |
Timoteivn 10 |
Sandnes |
1951 |
|
Svendson |
Tove |
Borgvn 23 |
Sandnes |
1978 |
|
Svendson |
Stale |
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 wrong:SELECT * FROM Persons WHERE FirstName=Tove |
For numeric values:
This is correct:SELECT * FROM Persons WHERE Year>1965This is wrong:SELECT * FROM Persons WHERE Year>'1965' |
The LIKE condition is used to
specify a search for a pattern in a column.
SELECT column FROM tableWHERE column LIKE pattern |
A "%" sign can be used
to define wildcards (missing letters in the pattern) both before and after
the pattern.
The following SQL statement will
return persons with first names that start with an 'O':
SELECT * FROM PersonsWHERE FirstName LIKE 'O%' |
The following SQL statement will
return persons with first names that end with an 'a':
SELECT * FROM PersonsWHERE FirstName LIKE '%a' |
The following SQL statement will
return persons with first names that contain the pattern 'la':
SELECT * FROM PersonsWHERE FirstName LIKE '%la%' |