The GROUP BY shows how to group rows into different levels based on columns or expressions.
The purpose of the GROUP BY
clause is to combined set of rows into a unique value or expression instead of the duplicated rows that might be retrieve without the application of the GROUP BY
clause.
it is requires to use GROUP BY
clause with all non-aggregate columns. In SQL, when using aggregate functions like SUM()
, any non-aggregated column in the SELECT
statement must be included in the GROUP BY
clause.
The syntax:
SELECT
column1,
column2,
column3,
aggregate_function(column4)
FROM
table_name
WHERE
condition_statement
GROUP BY
column1, column2, column3 # non-aggregate columns
HAVING
column1,column2,column3
In the order of execution, group by clause comes after the from
clause as shown below:
MySQL evaluates the GROUP BY
clause after the FROM
and WHERE
clauses but before the HAVING
, SELECT
, DISTINCT
, ORDER BY
and LIMIT
clauses:

In practice, you often use the GROUP BY
clause with aggregate functions such as SUM
, AVG
, MAX
, MIN
, and COUNT
. The aggregate function that appears in the SELECT
clause provides the information for each group.
