
DeAnna B.
asked 03/20/23SQL select if duplicates with max value
Use a SQL statement to find out the names of students whose marks are over 80 in all of their courses
Name course mark
Alice Art 81
Alice Math 74
Ben Art 76
Ben Math 90
Charles Art 81
Charles Math 100
Charles English 90
3 Answers By Expert Tutors
There is a simpler sql to answer the question.using function MIN()
The sql below filters the results to only include students
whose minimum mark is greater than 80
SELECT Name
FROM STUDENTS
GROUP BY Name
HAVING MIN(mark) > 80;
David L. answered 05/18/23
SQL expert, fantastic teacher, complete courses or help with 1 query
Unfortunately, Rize's query is incorrect. His answer is
The problem with Rize's answer is that the subquery has no WHERE clause. The subquery should give us the number of courses for the same student as in the outer query, not the total number of courses for all students.
With the given data, Rize's subquery always returns 3, the total number of courses in the students table. But Ben and Alice each took 2 classes, so even if all their marks are > 80, their value of COUNT(DISTINCT course) is 2, and Ben and Alice can never be returned by this query.
The minimal fix for Rize's query is to put in the missing WHERE clause so that the subquery give us the number of courses for the same student in the outer query.
This converts the subquery into a correlated subquery, which requires the use of table aliases.
Here's another way to do this problem:
In this version, I have two subqueries. Subquery #1 gets each Name, along with the number of courses with marks > 80 for that Name. Subquery #2 gets each Name, along with the number of courses that Name.
I then join the output of the two subqueries on the Name, and filter out Names where the number of courses with marks > 80 is not the same as the total number of courses.
And here's yet another version:
Some databases use "MINUS" instead of "EXCEPT". Both are used to remove rows in the output from the second query that are also in the output of the first query.
It is common for more than one query to accomplish the same goal.
Rize S. answered 03/23/23
Master's in MISM, 25 yrs Exp: SQL Specialist
Assuming the table name is "students", the SQL statement to find out the names of students whose marks are over 80 in all of their courses is:
SELECT Name
FROM students
WHERE mark > 80
GROUP BY Name
HAVING COUNT(DISTINCT course) = (SELECT COUNT(DISTINCT course) FROM students)
This query uses the GROUP BY and HAVING clauses to group the data by student name and count the number of distinct courses for each student, then filters for only those students who have marks greater than 80 in all of their courses.

David L.
05/18/23
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
David L.
05/18/23