Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML

Print Version

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

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

Enjoy this website?

  • Share
  • Add this page to your Favorites
  • Link to this page (copy/paste into your own website or blog):
  • Link to Quackit using one of these banner ads.
  • Help support Quackit by making a donation

Oh, and thank you for supporting Quackit!

© Copyright 2000 - 2010 Quackit.com