Finding rows with same value
January 22, 2026
Found this wonderful interview question asked to someone on X, thought it was easy at first, but it was nice to learn about the solution. Question goes like this :
You have a table named Students with columns StudentID, FirstName, LastName, and Score. Write an SQL query to find the names of students who have the same scores.
The solution goes like this: First find which scores are duplicated and that can be done like this
SELECT Score
FROM Students
GROUP BY Score
HAVING COUNT(*) > 1;This returns only the score values that appear more than once. (not the entire student rows, because we are selecting only scores) Now lets return the name of the students
SELECT s.FirstName, s.LastName, s.Score
FROM Students s
WHERE s.Score IN (
SELECT Score
FROM Students
GROUP BY Score
HAVING COUNT(*) > 1
)
ORDER BY s.Score, s.LastName, s.FirstName;-
The inner query here finds duplicated scores (like 85, 90) like we saw in step 1.
-
The outer query returns students whose Score is in that set.
-
Let's
ORDER BYto make it easy to read (sort byscore first, and then if same scores then sort by last name, and if even that is same then sort by firstname (default is ascending ofcourse.))