Sunday 27 December 2015

HAVING clause in SQL

HAVING clause in SQL used for arrangement or sorting by specific condition just like WHERE clause whereas these two clauses will be used as scenarios as following:
  1. Use WHERE clause if restriction or data filtering is before grouping and use HAVING clause if the restriction or data filtering is after grouping.
  2. Use WHERE clause for restricting a row and use HAVING clause for restricting a group.
  3. WHERE clause can be used individually whereas HAVING clause can be used only in conjunction with GROUP BY clause.
  4. WHERE clause could not be used with aggregate functions whereas HAVING can be used with aggregate functions.
Example:
  1. Select Deptnumber, Count (*) from EMP GROUP BY Deptnumber HAVING Count (*) > 5
  2. Select Count (*) from EMP WHERE Job=’Clerk’ GROUP BY Deptnumber Having Count (*) > 1
Query 1 retrieves the data of number of employees working in each department having count > 5.
Query 2 retrieves the data of number of Clerks working in each department having count > 1.

No comments:

Post a Comment