The WHERE clause is used to specify a selection criterion.
The WHERE Clause
To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.
Syntax
SELECT column FROM table |
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 !=
Using the WHERE Clause
To select only the persons living in the city "Sandnes", we add a WHERE clause to the SELECT statement:
SELECT * FROM Persons |
"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 | Stavanger | 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 |
Using Quotes
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: This is wrong: |
For numeric values:
This is correct: This is wrong: |
The LIKE Condition
The LIKE condition is used to specify a search for a pattern in a column.
Syntax
SELECT column FROM table |
A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
Using LIKE
The following SQL statement will return persons with first names that start with an 'O':
SELECT * FROM Persons |
The following SQL statement will return persons with first names that end with an 'a':
SELECT * FROM Persons |
The following SQL statement will return persons with first names that contain the pattern 'la':
SELECT * FROM Persons |
No comments:
Post a Comment