SQL Where

The WHERE clause allows you to narrow down the result set to only those that you're interested in.

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.

Actually, in the previous lesson we did use a WHERE clause when we selected records from multiple tables. Here's a closer look at the WHERE clause.

SQL WHERE Syntax

SELECT * FROM table_name
WHERE column_name = 'criteria';

Example

SQL WHERE Statement

SELECT * FROM Individual
WHERE FirstName = 'Homer';

Source Table

IndividualIdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike

Result

Given there are 3 people with the first name of Homer, the results will look like this:

IndividualIdFirstNameLastNameUserName
2HomerSimpsonhomey
3HomerBrownnotsofamous
5HomerGainnoplacelike

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

IndividualIdFirstNameLastNameUserName
3HomerBrownnotsofamous

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

IndividualIdFirstNameLastNameUserName
2HomerSimpsonhomey
3HomerBrownnotsofamous
5HomerGainnoplacelike
4OzzyOzzbournesabbath