Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Using subquerires in conjunction with the IN clause.
Subqueries are one of the most advanced concepts to learn in SQL query writing. Seeing lots of examples and getting lots of practice will help solidify the concept.
As you begin using subqueries, be advised that a poorly structured subquery written against a large table or tables can impact overall query performance. Be careful if you are writing subqueries against data sets that consume tables with row counts in the million-plus row range.
This course does not cover the concept called Correlated Subqueries, which are slightly different in how they tie in with the outer query. Most of the time a regular subquery will do what you need, but correlated subqueries can be handy, too. These are especially heavy weight on the database engine, as they run the subquery many times; once per row in the outer query.
See all of the SQL used in Querying Relational Databases in the Querying Relational Databases Cheat Sheet.
In this video, we're going to see how to use the IN keyword with a subquery.
Let's have a quick reminder of what the IN clause is.
You can use the IN keyword in your WHERE statement to enumerate of a list of things
to filter by.
Lets say we wanted to see specific car sales for ID's 1, 3, and 5.
Now, let's say we don't know exactly which car IDs we need.
This is where a subquery can help us out.
If we wanted to see all sales of cars with the model year of 2015,
we can replace this enumerated list of IDs with a query
that gets us the car IDs that meets our criteria.
First, let's write the query that gets the IDs we want.
So SELECT FROM
Car WHERE ModelYear = 2015.
This becomes our subquery that we can put inside
the parentheses replacing 1, 3, and 5.
You can also use a subquery in a NOT IN, as well.
Let's say, we really wanted to see all car sales except for the model year 2015.
We just have to add NOT In front of IN to get a different result.
The one trick to remember here is that you can only
select one column in your subquery.
if you have more than one you'll get an error.
So to review.
You can use a subquery in an IN clause.
When writing a subquery in this way you should only return one column of data.
This creates a set of values in the IN clause to search for.
Instead of writing the set manually ourselves,
we can get the database to do the heavy lifting for us.
[SOUND] You can also use a subquery in a NOT IN clause.
You need to sign up for Treehouse in order to download course files.Sign up