203 — Subqueries

Intermediate

Nest one query inside another to answer complex questions in a single statement. Subqueries let you filter, compare, and derive data dynamically — no hardcoded values needed.

Learning Objectives

1
Understand what subqueries are and when to use them
2
Write scalar subqueries for dynamic comparisons
3
Use IN and NOT IN with subqueries for set-based filtering
4
Apply EXISTS and NOT EXISTS for existence checks
5
Build correlated subqueries that reference the outer query
6
Use subqueries in the FROM clause (derived tables)
7
Choose between subqueries and JOINs
Step 1

What is a subquery?

See a subquery in action and understand the concept of a query nested inside another query.

Commands to Run

SELECT AVG(price) FROM products;
SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products) ORDER BY price DESC;

What This Does

A subquery is a SELECT statement inside another SQL statement, enclosed in parentheses. The database runs the inner query first (average price), then uses that result in the outer query (find products above average). Without subqueries, you would need to run two separate queries and manually plug the average into the second one. Subqueries make this automatic.

Expected Outcome

The first query shows the average product price (a single number). The second query returns all products priced above that average. Notice you didn't have to type the average value yourself — the subquery calculated it dynamically.

Pro Tips

  • 1
    Read subqueries from the inside out: first understand what the inner query returns, then read the outer query
  • 2
    Subqueries always go inside parentheses
Was this step helpful?

All Steps (0 / 10 completed)