CMD Guide
HomeDatabasesSQL Practice Problems

Winning Candidate

Problem

You are given two tables. Candidate lists every person who can be voted for; Vote records one row per ballot cast.

Table: Candidate

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| name        | varchar  |
+-------------+----------+
id is the PRIMARY KEY (column with unique values).
Each row holds the id and name of one candidate.

Table: Vote

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| candidateId | int  |
+-------------+------+
id is an auto-increment PRIMARY KEY (column with unique values).
candidateId is a FOREIGN KEY referencing Candidate.id.
Each row records the candidate who received the i-th vote.

Goal

Report the name of the winning candidate — the one who received the largest number of votes. The test cases are generated so that exactly one candidate wins, so you never have to break a tie.

The shape of the answer

This is the classic count-then-rank pattern that shows up everywhere in SQL: pair a child table against its parent, count the children per parent, sort by that count, and keep the top one. Read the four moving parts before the query so the SQL reads like prose:

The only subtle decision is which side of the join to start from and which column to group on. Both choices below are deliberate, and the Pitfalls section explains why.

diagram
diagram

Solution (MySQL 8)

The whole problem is four clauses. This page targets MySQL 8; the dialect matters for the grouping rules discussed below, and for the -- comment requiring a trailing space.

-- Winning candidate: count votes per candidate, take the top one
SELECT   c.name
FROM     Candidate c
         LEFT JOIN Vote v ON v.candidateId = c.id
GROUP BY c.id
ORDER BY COUNT(v.id) DESC
LIMIT    1;

Two deliberate choices make this both correct and strict-mode-clean:

Walking through it step by step

Step 1 — LEFT JOIN

Start from Candidate and LEFT JOIN Vote. The left join is what guarantees every candidate appears even with zero votes — their vote columns simply come back NULL. A plain INNER JOIN would silently drop any candidate nobody voted for.

+------+--------+------+---------------+
| c.id | c.name | v.id | v.candidateId |
+------+--------+------+---------------+
|  1   |  A     | NULL | NULL          |  -- A got no votes
|  2   |  B     |  1   |  2            |
|  2   |  B     |  4   |  2            |  -- B appears once per vote
|  3   |  C     |  3   |  3            |
|  4   |  D     |  2   |  4            |
|  5   |  E     |  5   |  5            |
+------+--------+------+---------------+

Notice candidate B occupies two rows — one per vote received. That multiplicity is exactly what the next step counts.

Step 2 — GROUP BY c.id

GROUP BY c.id collapses all rows that share a candidate id into a single output row. After this, there is one row per candidate, and we can ask an aggregate question of each group.

+------+--------+
| c.id | c.name |
+------+--------+
|  1   |  A     |
|  2   |  B     |   -- B's two vote rows are now one group
|  3   |  C     |
|  4   |  D     |
|  5   |  E     |
+------+--------+

Step 3 — ORDER BY COUNT(v.id) DESC

COUNT(v.id) counts how many non-NULL vote ids fell into each group — that is each candidate's tally. Counting v.id rather than * matters: for candidate A the joined v.id is NULL, so COUNT(v.id) is correctly 0, whereas COUNT(*) would wrongly report 1. DESC puts the biggest tally on top.

+--------+----------------+
| c.name | COUNT(v.id)    |
+--------+----------------+
|  B     |  2             |  <- winner floats to the top
|  C     |  1             |
|  D     |  1             |
|  E     |  1             |
|  A     |  0             |
+--------+----------------+

Step 4 — LIMIT 1

The list is already sorted with the winner first, so LIMIT 1 simply keeps the top row.

+--------+
| name   |
+--------+
|  B     |
+--------+

Pitfalls

Source

Problem adapted from LeetCode 574, Winning Candidate. Grouping and strict-mode behavior verified against the MySQL 8 Reference Manual, section 12.20.3 — MySQL extends the standard SQL use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause… provided they are functionally dependent on the GROUP BY columns, with ANY_VALUE() documented (section 14.18.1) as the escape hatch for the non-dependent case. Comment syntax per the MySQL 8 manual, section 11.7 (the -- sequence must be followed by whitespace).

🤖 Don't fully get this? Learn it with Claude

Stuck on Winning Candidate? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Winning Candidate** (Databases) and want to truly understand it. Explain Winning Candidate from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Winning Candidate** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Winning Candidate** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Winning Candidate** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes