Ad space (banner)
🗄️SQL Lessons
Lesson 9 / 50

Introduction to Subqueries

This lesson introduces subqueries — a SQL statement nested inside another one — for searches you can't express with a simple condition alone. It's for anyone searching "SQL subquery tutorial."

A subquery is a query embedded inside another query, useful for something like "students who scored above the class average," which a plain condition can't express. The inner query runs first, and its result feeds the outer query.

The example computes the average score with an inner query, (SELECT AVG(score) FROM students), and uses that value as the right-hand side of the outer WHERE score >. Try running just the parentheses on their own first — seeing exactly what value comes out makes the whole thing click.

A common early mistake is comparing with = when the subquery might return multiple rows — that only works if the subquery returns exactly one value; for multiple rows you need IN or EXISTS instead. It feels a bit tangled at first, but the trick is "read from the inside out" — once that clicks, subqueries become a versatile tool for comparing against aggregates or filtering by conditions defined in another table.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)