Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Filtering on More than One Condition2:51 with Andrew Chalkley
You're not restricted to just using one condition, you can test rows of information against multiple conditions. You can choose whether you retrieve rows that match both of your conditions or either of them.
You can compare multiple values in a
WHERE condition. If you want to test that both conditions are true use the
AND keyword, or either conditions are true use the
SELECT <columns> FROM <table> WHERE <condition 1> AND <condition 2> ...; SELECT <columns> FROM <table> WHERE <condition 1> OR <condition 2> ...;
SELECT username FROM users WHERE last_name = "Chalkley" AND first_name = "Andrew"; SELECT * FROM products WHERE category = "Games Consoles" AND price < 400; SELECT * FROM movies WHERE title = "The Matrix" OR title = "The Matrix Reloaded" OR title = "The Matrix Revolutions"; SELECT country FROM countries WHERE population < 1000000 OR population > 100000000;
See all of the SQL used in SQL Basics in the SQL Basics Cheat Sheet.
What happens when you want to use more than one condition?
Depending on what question you want to ask, you can use either the AND
keyword or the OR keyword.
Let's look at a general example first with one condition.
To add a second condition you add the appropriate keyword,
then the next condition.
Let's ask a question that includes two conditions.
What books in our library were authored by J.K. Rowling before the year 2000?
Let's remind ourselves of the table's structure.
We want to select the title, and then we want to compare the author and
the first_published columns.
So, SELECT title FROM books
WHERE author = "J.K.
first_published < 2000.
Using the AND keyword means that the row has to satisfy both conditions.
If I were to swap it out with an OR, it will retrieve books by J.K.
Rowling OR books first published before 2000.
As you can see, using the wrong keyword when combining conditions can
present very different results.
Let's ask another question.
What books do we have in the library authored by Ernest Klein or Andy Weir?
Let's select author this time too.
WHERE author = "Ernest Cline" OR
author = "Andy Weir".
We use OR rather than AND because the AND tests if every condition is satisfied.
Since the author cannot be both, Ernest Cline or
Andy Weir at the same time, no results will come back.
If we use OR we don't mind which condition is true.
As long as one of the conditions is true, the row will be returned.
To recap, the AND and OR keywords can be used to chain conditions together.
With the AND keyword all conditions need to be met.
With the OR keyword, only one condition needs to be met.
Combining the AND and OR keywords with multiple conditions can get complex.
I'll include some examples and details in the teacher's notes for you to refer to.
You need to sign up for Treehouse in order to download course files.Sign up