GROUP BY
GROUP BY

GROUP BY

Multi-select
Status
Done

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 HAVINGSELECTDISTINCTORDER BY and LIMIT clauses:

image

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

image

MySQL GROUP BY Examples:

Example 1:  Basic MySQL GROUP BY example

Example 2: Using MySQL GROUP BY with aggregate functions

Example 3:  MySQL GROUP BY with expression example

Example 4:  Using MySQL GROUP BY with HAVING clause example

Example 5: Grouping by Multiple Columns

Example 6: The GROUP BY clause vs. DISTINCT clause