Skip to main content

Using HAVING and GROUP BY in SQL

HAVING:
  • The HAVING clause used to filter records from of group of data with certain condition
  • The HAVING is used along with Aggregate Function. 
GROUP BY:
  • The GROUP BY is used to group record .
  • It can be used along with HAVING clause.
Example.
Employee
 id     Emp_name      Age         Salary Dept_id Location
 1 Jebas  35 55000 2 TVL
 2             Thomas  30 70000 1 TVL
 3 Mark              25 55000 2 TEN
 4         Harry  42 55000 2 TUTY
 5 Willam  45 70000 1 TUTY
 6 James  32 45000 3 TEN
 7 Mock  22 45000 3
 KOVI
 8 Sherin  23 12000 7 TUTY
SELECT location,count(location ) Number_of_Employee
  FROM Employee GROUP BY location ;
This statement returns the number of employee come from various location.
 Location Number_of_Employee
 KOVI       1
 MDY        1
 TEN 2
 TUTY 2
 TVL 2

SELECT dept_id , SUM(salary) TOTAL_SALARY 
  FROM Employee  GROUP BY dept_id   ;
This statement return total salary in each department
Employee
 Dept_id TOTAL_SALARY
 1140000
 265000
 390000
 7    12000

HAVING clause

  SELECT dept_id  
  FROM Employee  GROUP BY dept_id  HAVING COUNT(dept_id)>2  ;
This statement to find department in which more than two employee work.

 Dept_id
 2


Thank You. Like Share and Subscribe 👍 Followlect.com

Comments