The difference between the having and where clause is best illustrated by an example. Suppose we have a table called
class as shown below:
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;
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;
where clause, the query check
where first before doing
select student, sum(grade) as s from class where grade >5 group by student having s >8 ;
Note: You can see clearly that
having clause works with AGGREGATE function such as max, sum, count,...etc.
Whereclause works with the condition of each row.
Havingclause works with the condition of AGGREGATE function for group.(It usually comes after