This tutorial explains the difference between WHERE and HAVING clause in GROUP BY in SQL.
Sample Data
First we need to filter out all the product codes having value greater than 100 and then sum up sale by ID. Then keep only those IDs having sum of sales less than or equal to 5000.
Sample Data
Task
Create Sample Data in SAS
data temp;SQL Code : Subsetting Data
input ID Sale ProductCode;
cards;
1 2500 35
1 3000 75
2 5000 65
2 3500 125
3 2500 25
3 2000 255
;
run;
proc sql;
select ID, sum(Sale) as total_sale
from temp
where ProductCode <= 100
group by ID
having total_sale <= 5000;
quit;
![]() |
Output Data |
Key Difference
The WHERE condition is applied before the grouping occurs. Whereas, the HAVING condition is applied after the grouping occurs.