Skip to content
Codewilds

Lesson 26 of 30 · Advanced Queries

SQL Subqueries: IN, EXISTS and Scalar Subqueries

medium20 XP2 min read

Some questions need the answer to another question first. Which heroes are richer than average? First you need the average. A subquery is a SELECT inside another statement, wrapped in parentheses. SQL runs it to get the value or the list that the outer query needs.

Scalar subqueries: one value

SELECT name, gold
FROM heroes
WHERE gold > (SELECT AVG(gold) FROM heroes);

The inner query returns a single value (447.33…), so the outer query can compare against it like any number. A subquery that returns one row with one column is called scalar. You can't write WHERE gold > AVG(gold), because aggregates aren't allowed in WHERE (misuse of aggregate function AVG()). That's exactly the gap a subquery fills.

IN: a list of values

When the subquery returns a whole column, test membership with IN:

SELECT name
FROM heroes
WHERE id IN (SELECT hero_id FROM completions WHERE quest_id = 10);

The inner query lists the heroes who finished Dragon Sighting (quest 10): ids 3 and 8. The outer query keeps the heroes whose id is in that list, Cyra and Hugo. NOT IN keeps the others, for example the items nobody has ever bought:

SELECT name FROM items
WHERE id NOT IN (SELECT item_id FROM purchases);   -- Crown of Stars

EXISTS: is there at least one row?

EXISTS (subquery) is true when the subquery returns any row at all. It's usually correlated, meaning it refers to the row of the outer query:

SELECT g.name
FROM guilds g
WHERE EXISTS (
  SELECT 1 FROM heroes h
  WHERE h.guild_id = g.id AND h.level >= 20
);

For each guild, SQLite looks for a hero of that guild at level 20 or above: the Iron Wall and the Arcane Circle qualify. NOT EXISTS finds the opposite, such as guilds without any heroes. The SELECT 1 is a convention: EXISTS only checks whether a row exists, not what's in it.

Many subqueries can also be written as joins. Use whichever states the question more clearly.

The tables for this lesson:

Table Columns
heroes id, name, class, level, gold, guild_id, joined
quests id, title, region, difficulty ('easy', 'medium' or 'hard'), reward
completions hero_id, quest_id, completed_on (one row per hero per finished quest)

Common mistakes

  • NOT IN with NULLs. SELECT name FROM guilds WHERE id NOT IN (SELECT guild_id FROM heroes); returns nothing, although the Dawn Wardens have no heroes. Some heroes have no guild (NULL), and x NOT IN (…, NULL) is never true. Filter the NULLs out with WHERE guild_id IS NOT NULL, or use NOT EXISTS.
  • A "scalar" subquery that returns several rows. Most databases raise an error; SQLite silently uses the first row. Make sure it really returns one value.
  • Forgetting the parentheses around the subquery.

Assignment

List the heroes who are richer than the average hero and have completed at least one 'hard' quest. Show the columns name and gold, richest hero first. Use a subquery for each condition.

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The SQL cheat sheet has every topic of Learn SQL on one page.

Lesson last updated on .

Write code ↓
SQL+20 XP

Lesson 26 is part of the full course. The first 7 lessons are free.

Premium lesson

Unlock the full Learn SQL course

  • All 30 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 7 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.