Skip to content
Advertisement

SQL: Why do I not get the same output with the two queries below?

I am trying to find Students who got all possible different grades. If you receive an 18 you pass the course and the highest number is 30. Thus, if you have received 13 different grades which are higher than 17 you have in turn received all possible passing grades. The first query returns 0 rows and the second one returns one with a student which has received all possible passing grades.

select sid, name, count(grade)
from student natural join exam 
group by sid, name
having count(distinct grade > 17) = 13; 



select sid, Name
from exam natural join student
group by sid
having count(distinct grade) = ( select count(distinct grade) 
                             from exam );

Thank you in advance!

Advertisement

Answer

You should not use natural join. It makes the query quite unclear on what it is doing.

In any case, this code:

count(distinct grade > 17)

can only return 0, or 1, or 2. Why? Because it is counting the distinct values of a boolean expression. And a boolean expression only has two values (plus NULL).

Hence, it will never be equal to 13.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement