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
Winning Candidate - SQL Solution INPUT TABLES Candidate Table id name 1 Alice 2 Bob 3 Charlie Vote Table id candidateId 1 2 2 2 3 1 4 2 5 3 ALGORITHM STEPS 1 Count Votes GROUP BY candidateId COUNT(*) for each 2 Order Results ORDER BY count DESC Most votes first 3 Join Tables Connect Vote to Candidate on id 4 Get Winner LIMIT 1 to get top Return name only Vote Counts: Bob (id:2): 3 votes Alice (id:1): 1 vote Charlie (id:3): 1 vote FINAL RESULT Winner: Bob (3 votes - highest) Output: { name: "Bob" } OK - Verified Key Insight: Use GROUP BY with COUNT(*) to aggregate votes per candidate, then ORDER BY DESC with LIMIT 1 to find the winner. JOIN with Candidate table to get the name. SELECT name FROM Candidate c JOIN Vote v ON c.id = v.candidateId GROUP BY c.id ORDER BY COUNT(*) DESC LIMIT 1 TutorialsPoint - Winning Candidate | Optimal Solution
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