You are on page 1of 30

Group By and Having clause

Group By Clause:
 Sometimes, rather than retrieving individual records, you want
to know something about a group of records,
 The GROUP BY clause is used in a SELECT statement to
collect data across multiple records and group the results by
one or more columns.
 The GROUP BY clause returns one row for each group. In
other words, it reduces the number of rows in the result set.
Having Clause
 The having clause, is just like the where clause, that filters
the results in aggregated data.
 The Where clause cannot be used in the aggregated data,
so SQL having clause is introduced to filter the results.
 The having SQL clause is used with the Group by clause.
 You can only use those column names in the having
clause that are appeared in the Group by clause.
SQL HAVING Clause

 Having clause is used to filter data based on the group


functions.
 This is similar to WHERE condition but is used with
group functions.
 Group functions cannot be used in WHERE Clause but
can be used in HAVING clause.
 A group by is a query that takes a table and summarizes it
into another table.
 You summarize the original table by grouping the original
table into subsets (based upon the attributes that you
specify in the group by).
 The Having is simply equivalent to a WHERE
clause after the group by has executed and before the
select part of the query is computed.
 If you want to select the department that has total salary
paid for its employees more than 25000, the sql query
would be like;
 SELECT dept, SUM (salary) 
FROM employee 
GROUP BY dept 
HAVING SUM (salary) > 25000 
 When WHERE, GROUP BY and HAVING clauses are
used together in a SELECT statement,
 the WHERE clause is processed first, then the rows that
are returned after the WHERE clause is executed are
grouped based on the GROUP BY clause.
 Finally, any conditions on the group functions in the
HAVING clause are applied to the grouped rows before
the final output is displayed.

You might also like