Solve SQL problem in 2 different ways

The Problem

we have 2 tables

  1. user Table
  2. vote Count Table

as given below:

name

idname
1A
2B
3C

votCount

idvote
13
24
37

Write a query such that it will show only the name of the user that has the top vote and it has to be in one query without the sub query. First let’s see how it is done with sub queries. 

SELECT name.name 
FROM name
INNER JOIN votCount
ON votCount.n_id = name.id
WHERE votCount.vote = (SELECT MAX(votCount.vote) FROM votCount)

Now let’s see how we can do it in one query and which will take less compute time. 

SELECT name.name 
FROM name
INNER JOIN votCount
ON votCount.n_id = name.id
ORDER BY votCount.vote DESC
LIMIT 1;

Turns out the query was a lot simpler than I thought. But it took me over half an hour to figure it out. Which is probably a bit embarrassing. Since this was asked in an interview question where you should have got it within few minutes. 

5 2 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x