We can include as many conditions to our query as we want. We can set multiple conditions on the same column or we can use two or more columns to help decide what should be returned. Two conditions could be given and if either of them contain a match, the corresponding rows will be returned.

When we have two or more conditions and we want every condition to be met, we use the keyword AND. When we have two or more conditions and we want any one of the conditions to be met, we use the keyword OR.

Let’s say we wanted to limit our search to the names of a few dogs, and we also wanted only those dogs who have been with their owners for at least 2 years. This is really the combination of the two examples in the IN clause section. We will use the keyword AND because we want both conditions to be met.

SELECT NameOfDog, BreedOfDog, ColorOfDog

FROM Dogs

WHERE NameOfDog IN ('Pluto', 'Lassie', 'Benji', 'Old

Yeller')

AND MonthsWithOwner > 24;

 

OUTPUT
NameOfDog         BreedOfDog         ColorOfDog
———-                  ————-               ——————-

Pluto                     Bloodhound         Yellow Orange
Benji                     Tibetan Terrier     Black

(2 row(s) affected)

 

Adding the keyword AND between the two conditions tells the database they both have to be met for a row to be returned.

If we switched this up a bit and used the keyword OR, then our results would include dogs whose names are in the list OR who have been with their owners for at least 2 years, even if their names are not in the name list.

SELECT NameOfDog, BreedOfDog, ColorOfDog

FROM  Dogs

WHERE NameOfDog IN ('Pluto', 'Lassie', 'Benji', 'Old

Yeller')

OR MonthsWithOwner > 24;

 

OUTPUT (Modified)

NameOfDog         BreedOfDog         ColorOfDog
—————–          ————-               —————-
Odie                      Abruzzenhund       Yellow
Pluto                     Bloodhound           Yellow Orange
Hercules               Carolina Dog         Black and White
Hercules               Carolina Dog         Black
Hercules               Carolina Dog         White and Yellow
Clifford                 Carolina Dog          Red
Clifford                 Bulldog                   Yellow
Clifford                 Carolina Dog         Brown
Clifford                 Carolina Dog         Tan
Clifford                 Carolina Dog         White

(116 row(s) affected)

We will occasionally make our queries a little too specific and no data may result. If we are sure we are asking the right question, no data returned is OK.

I

Want to follow along on your own database?

Do you want to follow along with the examples?  We have created a sample database you can use to follow along and try in your own database.  Go to the download page and follow the instructions.  Have fun on the SQL trail!