Available Tables

Next →

Writing Basic Subqueries

A subquery is a query nested inside another query. It’s often used to compute a value that the outer query can use in its logic.

Subqueries are enclosed in parentheses and can appear in the WHERE, FROM, or SELECT clauses.

Example: Subquery in WHERE

To find students older than the average age:

SELECT name FROM students
WHERE age > 
(SELECT AVG(age) FROM students);

Here, the subquery (SELECT AVG(age) FROM students) runs first and returns the average age. The outer query then finds students whose age is greater than that result.

Subqueries are powerful for filtering, comparing, and transforming data dynamically. In later levels, you’ll explore more advanced uses like correlated subqueries and subqueries in the FROM clause.