Intermediate Topic 18 of 51 Databases
Subqueries
Queries nested within other queries.
How it works
A subquery is a query nested inside another, used in SELECT, FROM, WHERE or HAVING. Scalar subqueries return one value, row and table subqueries return sets, and correlated subqueries refer to columns of the outer query and are evaluated for each outer row conceptually. Operators such as IN, EXISTS, ANY and ALL compare against subquery results. Many subqueries can be rewritten as joins or common table expressions.
Step-by-step walkthrough
- The inner query runs, for example the average price.
- Its result becomes a value or list.
- The outer query uses it, WHERE price > that average.
- A correlated subquery re-runs for each outer row.
- Often a join is faster.
Where it is used
Finding customers who ordered above the average amount, products never sold with NOT EXISTS, and computing derived tables for reports use subqueries.
Common pitfall
Correlated subqueries can be slow if executed per row, though optimizers often unnest them. NOT IN with NULLs in the subquery returns nothing, a notorious trap; use NOT EXISTS. A scalar subquery returning more than one row raises an error. Deep nesting hurts readability, so prefer CTEs for complex logic.
Where it fits in the course
Subqueries is topic 18 of 51 in Databases, rated Intermediate. It follows Data Types in SQL. The next topic is Views.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Subqueries?
Where do people use Subqueries?
What is the most common mistake with Subqueries?
What should I learn before this topic?
How can I practice it?
Is Subqueries hard to learn?
How long does it take to learn Subqueries?
Which topics are related to Subqueries?
What should I study after Subqueries?
Related topics
- Data Types in SQL (Databases)
- Views (Databases)
- Entity-Relationship Modeling (Databases)
- Indexes (Databases)