The difference between the having and where clause is best illustrated by an example. Suppose we have a table called class
as shown below:
student | subject | grade |
---|---|---|
A | math | 8 |
A | physics | 5 |
B | math | 4 |
C | physics | 9 |
Or you can create a table and insert values like this:
create table class(
student varchar(20),
subject varchar(20),
grade int
);
insert into class(student, subject, grade)
values ('A','math',8),('A','physics',5),('B','math',4),('C','physics',9);
select student, sum(grade)
from class
group by student;
RESULT:
student | sum(grade) |
---|---|
A | 13 |
B | 4 |
C | 9 |
Note: In the result of this query, we can see that student A has two grades which are 5 and 8. So the sum of student A's grade is 13
select student, sum(grade)
from class
where grade >5
group by student;
RESULT:
student | sum(grade) |
---|---|
A | 8 |
C | 9 |
Note: With where
clause, the query check where
first before doing group by
select student, sum(grade) as s
from class
where grade >5
group by student
having s >8
;
student | s |
---|---|
C | 9 |
Note: You can see clearly that having
clause works with AGGREGATE function such as max, sum, count,...etc.
Where
clause works with the condition of each row.Having
clause works with the condition of AGGREGATE function for group.(It usually comes after group by
)