Group by and Having Clauses in SQL
Often used clauses with the aggregate functions.
Through this article, we’ll learn what is Group by and Having clauses, when to use these clauses and how they are different than the where clause. The questions on these two clauses are mostly asked in the interviews that are focused on SQL.
What Does the Group by Clause Do?
The SQL GROUP BY clause is often used with the SELECT
statement to group or arrange the rows together into multiple groups based on certain column(s) values. This GROUP BY
clause follows the WHERE
clause in a SELECT
statement and precedes the ORDER BY
clause.
The GROUP BY statement is often used with aggregate functions to group the result-set by one or more columns. These functions are:
COUNT()
: To count the number of records in a table.MAX()
: To find the maximum value of a column.MIN()
: To find the minimum value of a column.SUM()
: To find the sum of values of a column.AVG()
: To find the average of values of a column.
Note: we cannot use aggregate functions in
WHERE
clause.