Skip to content
Codewilds

Lesson 28 of 30 · Advanced Queries

SQL WITH Clause: Common Table Expressions (CTEs)

medium20 XP3 min read

Queries grow. A subquery inside a subquery inside a join soon becomes hard to read, because you have to start in the middle and work your way out. A common table expression (CTE) lets you give each step a name and write the steps top to bottom, like a recipe.

WITH … AS (…)

WITH guild_gold AS (
  SELECT guild_id, SUM(gold) AS total
  FROM heroes
  WHERE guild_id IS NOT NULL
  GROUP BY guild_id
)
SELECT g.name, gg.total
FROM guild_gold gg
JOIN guilds g ON g.id = gg.guild_id
WHERE gg.total > 1500
ORDER BY gg.total DESC;

WITH guild_gold AS (…) defines a temporary, named result (the total gold of each guild), and the main query below uses it like a table. The result: Iron Wall 2140, Arcane Circle 2120, Night Market 1530. A CTE only exists for the statement it belongs to; after the final ; it's gone.

Several CTEs

Separate several CTEs with commas, after a single WITH. A later CTE can use an earlier one:

WITH guild_gold AS (
  SELECT guild_id, SUM(gold) AS total
  FROM heroes
  WHERE guild_id IS NOT NULL
  GROUP BY guild_id
),
richest AS (
  SELECT MAX(total) AS top FROM guild_gold
)
SELECT g.name, gg.total
FROM guild_gold gg
JOIN guilds g ON g.id = gg.guild_id
JOIN richest r ON gg.total = r.top;   -- Iron Wall | 2140

Why not just nest?

Here is the same question with nested subqueries:

SELECT g.name, gg.total
FROM (SELECT guild_id, SUM(gold) AS total FROM heroes
      WHERE guild_id IS NOT NULL GROUP BY guild_id) gg
JOIN guilds g ON g.id = gg.guild_id
WHERE gg.total = (SELECT MAX(total) FROM
        (SELECT SUM(gold) AS total FROM heroes
         WHERE guild_id IS NOT NULL GROUP BY guild_id));

It works, but the guild totals are written twice and you have to read it inside out. With CTEs, each step has a name, appears once, and can be checked on its own: keep only the first CTE, end with SELECT * FROM guild_gold;, and look at the rows before you build the next step on top.

CTEs and views

A CTE lives for one query. To keep a query in the database under a name, save it as a view: CREATE VIEW guild_totals AS SELECT …;. After that, SELECT * FROM guild_totals; runs the saved query. You'll build one in this chapter's boss fight.

The tables for this lesson: heroes (id, name, class, level, gold, guild_id, joined), quests (id, title, region, difficulty, reward) and completions (hero_id, quest_id, completed_on, one row per hero per finished quest).

Common mistakes

  • A second WITH. Write WITH a AS (…), b AS (…), not WITH a AS (…) WITH b AS (…).
  • A comma before the main query. …), SELECT … is a syntax error. The last CTE is followed directly by the main SELECT.
  • Using a CTE in the next statement. It only exists inside its own statement.

Assignment

Find the heroes who earned more quest rewards than the average hero. Build it in three steps:

  1. A CTE named hero_rewards with one row per hero who completed quests: hero_id and total_reward, the sum of the reward of every quest that hero completed (completions joined to quests).
  2. A second CTE named average_reward with one column, avg_reward: the average total_reward in hero_rewards.
  3. A main query that shows name (from heroes) and total_reward for every hero whose total_reward is above avg_reward, highest first.

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 28 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.