Lesson 17 of 30 · Joins
Boss: SQL LEFT JOIN with GROUP BY, COUNT and SUM
The Guild Registrar blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
At the end of every year, the Guild Registrar — a stern old clerk with ink-stained gloves — renews the charter of every guild in the realm. A guild that is missing from the register is dissolved on the spot, so the Dawn Wardens, whom nobody has joined yet, are counting on you to get every row right.
Battle plan
This fight combines Chapter 3 with Chapter 2: a LEFT JOIN that keeps every guild, then GROUP BY with COUNT and SUM for each guild. Here are the guilds:
| id | name | city | founded |
|---|---|---|---|
| 1 | Silver Arrows | Eldermoor | 1987 |
| 2 | Iron Wall | Stonehold | 1952 |
| 3 | Arcane Circle | Mistvale | 1903 |
| 4 | Night Market | Eldermoor | 2011 |
| 5 | Dawn Wardens | Sunreach | 2023 |
Heroes point to their guild with heroes.guild_id, and their gold is in heroes.gold. Watch out for two traps that appear whenever you combine a LEFT JOIN with aggregates:
COUNT(*)counts rows, and an empty guild still has one row after theLEFT JOIN— the one with NULL in every hero column. SoCOUNT(*)reports 1 member.COUNT(h.id)skips NULLs and correctly reports 0.SUMof nothing is NULL, not 0. Here is one new tool for the fight:COALESCE(value, fallback)returns the value, or the fallback when the value is NULL.
SELECT COALESCE(NULL, 0) AS empty_guild, COALESCE(2140, 0) AS full_guild;
| empty_guild | full_guild |
|---|---|
| 0 | 2140 |
Remember to group by every guild column you select: GROUP BY g.id, g.name, g.city.
Assignment
The Registrar wants every guild in the realm, including guilds without members. Write one query that returns one row per guild with these columns, in this order:
guild— the guild's namecity— the guild's citymembers— how many heroes belong to the guild (0 for a guild without members)total_gold— the members' gold added up (0, not NULL, for a guild without members)
Sort the guilds by members, most first; guilds with the same number of members by total_gold, richest first. Heroes without a guild don't belong to any guild, so they don't count anywhere in this report.
Each passing test stamps one seal on the charter. Collect all eight seals to defeat the Guild Registrar and finish the chapter.
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
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 .