# 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:

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

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:

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
group by student;

RESULT:

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