Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where vs Having clause in SQL statement [duplicate]

Tags:

sql

Both SQL statements return the same result. So what is the difference when using where clause vs using a having clause?

Any idea?

select  
    min(internid), max(internid) 
from  
    v_intern
where   
    trainingterm= 'Fall - September' and trainingyear = '2020'
group by 
    trainingTerm, trainingYear 


select  
    min(internid), max(internid) 
from  
    v_intern
group by 
    trainingTerm, trainingYear 
having  
    trainingterm = 'Fall - September' and trainingyear = '2020' 
like image 990
aalhussein Avatar asked Aug 10 '26 10:08

aalhussein


1 Answers

In where clause you can not use the aggregate function.

In the Having clause you can use the aggregate function.

So In your query, If the requirement is something like min(internid) should be greater then X value then you can use It in the HAVING clause as WHERE clause does not serve that purpose as follows(But yes in the HAVING clause you can write the normal conditions too but that conditions are checked after groupping):

select min(internid), max(internid) from v_intern  
where trainingterm= 'Fall - September' and trainingyear ='2020'
group by trainingTerm, trainingYear
having min(internid) > x
like image 75
Popeye Avatar answered Aug 13 '26 00:08

Popeye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!