Description

Write a SQL query to find the name of the candidate with the most votes. In case of a tie, return the candidate whose name comes first alphabetically. **Output columns (in order):** name

Table:candidates
ColumnType
idINT
nameTEXT
Table:votes
ColumnType
idINT
candidate_idINT

Examples

Input:CREATE TABLE candidates (id INT, name TEXT); CREATE TABLE votes (id INT, candidate_id INT); INSERT INTO candidates VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO votes VALUES (1, 1), (2, 1), (3, 2);
Output:Alice
Explanation:

Alice has 2 votes (vote ids 1 and 2), Bob has 1 vote (vote id 3). Alice has the most votes, so she is the winner.

Input:CREATE TABLE candidates (id INT, name TEXT); CREATE TABLE votes (id INT, candidate_id INT); INSERT INTO candidates VALUES (1, 'Charlie'), (2, 'David'), (3, 'Eve'); INSERT INTO votes VALUES (1, 2), (2, 2), (3, 3), (4, 3), (5, 1);
Output:David
Explanation:

David and Eve are tied with 2 votes each, while Charlie has 1 vote. Since there's a tie for the most votes, returning the candidate whose name comes first alphabetically, which is David.

Input:CREATE TABLE candidates (id INT, name TEXT); CREATE TABLE votes (id INT, candidate_id INT); INSERT INTO candidates VALUES (1, 'Sarah'), (2, 'Mike'), (3, 'John'); INSERT INTO votes VALUES (1, 3), (2, 3), (3, 3), (4, 2), (5, 1);
Output:John
Explanation:

John has 3 votes, Mike has 1 vote, and Sarah has 1 vote. John clearly has the most votes, so he is the winning candidate.

Constraints

  • Handle ties by returning first alphabetically

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!