SQL Tutorial 0/85 lessons ~6 min read Lesson 29
Subqueries
A subquery is a SELECT inside another SQL statement.
Course progress0%
Focus
6 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
A subquery is a SELECT inside another SQL statement. They appear in FROM (derived table), SELECT (scalar), WHERE (predicate), or in EXISTS / IN.
Understanding the topic
Core concepts to understand:
- Scalar subquery: returns one value.
- Derived table:
FROM (SELECT ...) t. - Correlated subquery: references outer row — runs per row, slower.
EXISTS/INfor membership checks.- Often rewritable as JOINs or CTEs for clarity.
Syntax reference
Visual workflow / architecture:
bash
SELECT name,(SELECT count(*) FROM orders WHERE user_id = u.id) AS orders -- scalarFROM users uWHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.amount > 100); -- correlated
Real-world use
Subqueries answer questions like 'users with at least one order over $100', 'products never bought', 'top 10 customers per region'.
Best practices
- Prefer JOINs or CTEs for readability.
- Be cautious with correlated subqueries on big tables.
- Use EXISTS rather than IN for large sets.
Hands-on exercise
Interview preparation — practice these questions:
- Q1. Correlated vs uncorrelated subquery.
- Q2. EXISTS vs IN — when to choose which.
- Q3. Rewrite a subquery as a JOIN.
- Q4. Scalar subquery — what is it?
- Q5. Performance pitfalls of subqueries.
Ready to mark this lesson complete?Track your journey across the entire course.