SQL Intermediate: Joins, Subqueries and Design
Subqueries: Queries Inside Queries
In this lesson you will
- Use a subquery that returns one value
- Filter with IN and EXISTS
- Use a subquery in the FROM clause
Introduction
Sometimes you cannot write the answer in one step. "Which products cost more than the average?" first needs the average, then needs a comparison. A subquery is a SELECT inside another query, written in brackets. The inner query runs first and hands its result to the outer one.
A subquery that returns one value
That is the average price. You could copy that number into a second query, but then it would go stale. Instead nest it:
The inner query is calculated once, and the outer query compares each product to the result.
You can also show the value as a column, to see the comparison:
Quick quiz
In WHERE price > (SELECT AVG(price) FROM products), which part runs first?
A subquery that returns a list: IN
If the inner query returns one column of many rows, use IN.
Be careful: NOT IN returns nothing at all if the list contains a NULL. If the column can be empty, add WHERE column IS NOT NULL to the inner query, or use NOT EXISTS.
EXISTS
EXISTS asks "does the inner query return any row at all?". The inner query can look at the current outer row, which is called a correlated subquery.
This lists customers who have at least one shipped order. The SELECT 1 is a convention: EXISTS only cares whether a row exists, not what it contains.
Quick quiz
What does a correlated subquery do?
A subquery in FROM
A subquery can act like a temporary table. Give it an alias.
First the inner query calculates the value of each line item. Then the outer query averages them per category. The advanced course shows a cleaner way to write this with a WITH clause.
Try it yourself
List the products whose price is below the average price of their own category. Hint: use a correlated subquery that compares category to the outer product's category.
Summary
- A subquery is a
SELECTin brackets inside another query. - A single-value subquery works with
>,=and the other comparisons. INchecks a list andEXISTSchecks whether any row exists. PreferNOT EXISTSwhen NULLs are possible.- A subquery in
FROMacts like a temporary table and needs an alias.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading