#### what is the difference between having clause and group by statement in sql server

Total Post:341

Points:2389
1274  View(s)
Ratings:
Rate this:
I want to know what is the difference between having clause and  group by in sql server please tell me.
1. Post:281

Points:2003
##### Re: what is the difference between the having clause and group by statement in sql server

In SQL, the having clause and the group by statement work together when using aggregate functions like SUM, AVG, MAX, etc.

If we want to calculate the total salary that each employee has received, then we would write a SQL statement like this:

`select Emp_Name, sum(Emp_Sal) as TotalSalary from Employee group by Emp_Name;`

In the SQL statement above, you can see that we use the "group by" clause with the employee column. The group by clause allows us to find the sum of the salary for each employee.

Now, suppose we wanted to find the employees who received more than 1,0000  salary – this is assuming of course that the Employee table contains salary. This is when we need to use the HAVING clause to add the additional check to see if the sum of salary is greater than 1,0000 and this is what the SQL look like:

```
select Emp_Name, sum(Emp_Sal)as TotalSalary from Employee group by Emp_Name having sum(Emp_Sal) > 10000;```

So, from the example above, we can see that the group by clause is used to group column(s) so that aggregates (like SUM, MAX, etc) can be used to find the necessary information. The having clause is used with the group by clause when comparisons need to be made with those aggregate functions – like to see if the SUM is greater than 1,000, as in our example above.

Modified On Jan-27-2016 06:22:16 AM

#### CONTACT INFO

10-B Taskand Marg, Near Patrika Chauraha, Civil Lines, Prayagraj, UP, India-211001.
contact@mindstick.com
91-532-2400505

969-G Edgewater Blvd,Suite
793 Foster City-94404, CA (USA)
+1-650-242-0133