Winning Candidate - Problem

You are given two tables representing an election system:

Table: Candidate

  • id (int): Unique identifier for each candidate
  • name (varchar): Name of the candidate

Table: Vote

  • id (int): Auto-increment primary key for each vote
  • candidateId (int): Foreign key referencing the candidate who received this vote

Write a SQL query to find the name of the winning candidate - the candidate who received the most votes. The test cases guarantee that exactly one candidate wins the election.

Table Schema

Candidate
Column Name Type Description
id PK int Unique identifier for each candidate
name varchar Name of the candidate
Primary Key: id
Vote
Column Name Type Description
id PK int Auto-increment primary key for each vote
candidateId int Foreign key referencing the candidate who received this vote
Primary Key: id

Input & Output

Example 1 — Basic Election
Input Tables:
Candidate
id name
2 Bob
3 Alice
4 Carol
Vote
id candidateId
1 2
2 4
3 3
4 2
5 2
Output:
name
Bob
💡 Note:

Bob received 3 votes (vote IDs 1, 4, 5), Alice received 1 vote (vote ID 3), and Carol received 1 vote (vote ID 2). Bob has the most votes, so he wins the election.

Example 2 — Close Election
Input Tables:
Candidate
id name
1 John
2 Jane
Vote
id candidateId
1 1
2 2
3 1
4 1
Output:
name
John
💡 Note:

John received 3 votes (vote IDs 1, 3, 4) and Jane received 1 vote (vote ID 2). John wins with the majority of votes.

Constraints

  • 1 ≤ candidate.id ≤ 100
  • 1 ≤ vote.candidateId ≤ 100
  • 1 ≤ total votes ≤ 1000
  • Exactly one candidate wins the election

Visualization

Tap to expand
Finding the Winning CandidateVote TableidcandidateId1224334252Candidate Tableidname2Bob3Alice4CarolJOIN & GROUP BYCOUNT(*)Vote CountsnamecountBob3Alice1Carol1Winner: Bob
Understanding the Visualization
1
Join Tables
Connect Vote and Candidate tables
2
Group & Count
GROUP BY candidate and COUNT votes
3
Find Winner
ORDER BY count DESC, LIMIT 1
Key Takeaway
🎯 Key Insight: Use GROUP BY with COUNT to aggregate votes, then JOIN to get readable results
Asked in
Amazon 28 Microsoft 22 Facebook 18 Google 15
34.5K Views
High Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen