Clauses of Select Statment in SQL

HAVING Clause in SQL

When we use any aggregate functions in our SQL statement then we can't use the WHERE clause with these type of statement. For example if we use SUM function In SELECT statement using GROUP BY clause then we can not use the where clause. So if we want to apply the filter with GROUP BY Clause then we use HAVING Clause. The difference between WHERE and HAVING clause is, WHERE clause is used to apply the filter on column level and HAVING clause apply the filter on on group created by GROUP BY clause.

For example if we have a following table with some payment Record of customer:

customer_name city Payments
Tauqeer Karachi 18000
 Zia Lahore 5000
Noman Karachi 8000
Tauqeer Karachi 3000
Noman Karachi 4000
Zia Lahore 6000

 

Now from this table if we want to calculate and display the total payment of those customer whose total payments are grater the 50000. So for this purpose first we SUM the payments of the user in groups (using GROUP BY Clause)  and Then Apply the Filter (Condition) to select those customer whose payments grater then 20000 ( Using HAVING Clause).

SELECT customer_name, SUM(payments) AS Net_Payments FROM payments

GROUP BY customer_name

HAVING Sum(payments>20000) ;

First of all this statement create group by customer_name and then add the payments and then apply the filter if any of the selected record net_payment is grater then 20000 then it will be display.

 The above statement produced the following result :

customer_name Net_Payments
Tauqeer 21000