DIFFERENCES BETWEEN WHERE AND HAVING CLAUSE IN SQL:

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);

LET TRY SOME QUERIES WITH CORRESPONDING RESULTS:

Query 1: Extract student and sum of grade grouping by student

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

Query 2: Extract student and sum of grade( for any grade >5)

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

Query 3: Extract student and sum of grade( for any grade >5), and the sum of grade must be > 8

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.

CONCLUSION: