Skip to main content
Albero Academy

Subqueries

A query inside a query — compare against computed values.

Advanced Queries9 min

A subquery is a SELECT nested inside another statement. It lets you filter or compute against a value that itself needs a query — "students earning more than the average", "programmes with at least one placed student".

Subqueries in WHERE

compare to a computed value
-- Above the overall average package
SELECT name, package FROM students
WHERE package > (SELECT AVG(package) FROM students);
-- Membership with IN
SELECT name FROM students
WHERE programme_id IN (SELECT id FROM programmes WHERE city = 'Pune');

Correlated subqueries & EXISTS

EXISTS references the outer row
SELECT p.name FROM programmes p
WHERE EXISTS (
SELECT 1 FROM students s
WHERE s.programme_id = p.id AND s.status = 'placed'
);

Key takeaways

  1. 01A subquery is a SELECT nested in WHERE, FROM (derived table) or SELECT.
  2. 02Use it to compare against a computed value (e.g. the average).
  3. 03IN checks membership; EXISTS checks whether any matching row exists.
  4. 04A correlated subquery references the outer row and runs per row.

Finished this chapter?

Mark it complete to track your progress through SQL.