SQL Where
In the previous lesson, we used a SQL SELECT statement to retrieve all records from a database table. This is fine if we want to see every record, but what if we were only interested in some records? For example, what if we were only interested in individuals whose first name is "Homer"?
We could use the WHERE clause.
Using the WHERE clause, you can filter out only those records that satisfy a given condition.
SQL WHERE Syntax
SELECT * FROM table_name
WHERE column_name = 'criteria'
Example
SQL WHERE Statement
SELECT * FROM Individual
WHERE FirstName = 'Homer'
Source Table
| IndividualId | FirstName | LastName | UserName |
|---|---|---|---|
| 1 | Fred | Flinstone | freddo |
| 2 | Homer | Simpson | homey |
| 3 | Homer | Brown | notsofamous |
| 4 | Ozzy | Ozzbourne | sabbath |
| 5 | Homer | Gain | noplacelike |
Result
Given there are 3 people with the first name of "Homer", the results will look like this:
| IndividualId | FirstName | LastName | UserName |
|---|---|---|---|
| 2 | Homer | Simpson | homey |
| 3 | Homer | Brown | notsofamous |
| 5 | Homer | Gain | noplacelike |
Multiple Conditions
You can filter records based on more than one condition using operators. Two common operators are the AND and OR operators.
AND Operator
The AND operator filters the query to only those records that satisfy both the first condition and the second condition.
SELECT * FROM Individual
WHERE FirstName = 'Homer'
AND LastName = 'Brown'
Result
| IndividualId | FirstName | LastName | UserName |
|---|---|---|---|
| 3 | Homer | Brown | notsofamous |
OR Operator
The OR operator filters the query to only those records that satisfy either one or the other condition.
SELECT * FROM Individual
WHERE FirstName = 'Homer'
OR LastName = 'Ozzbourne'
Result
| IndividualId | FirstName | LastName | UserName |
|---|---|---|---|
| 2 | Homer | Simpson | homey |
| 3 | Homer | Brown | notsofamous |
| 5 | Homer | Gain | noplacelike |
| 4 | Ozzy | Ozzbourne | sabbath |
