MySQL : GROUP BY Statement

The GROUP BY statement in MySQL is used to group rows that have the same values into summary rows, like "find the total sales for each product" or "count the number of orders for each customer". 

Here's the basic syntax:


SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;

 

  • column1 is the column you want to group by.
  • aggregate_function can be COUNT, SUM, AVG, MIN, or MAX, among others, and is applied to column2.
  • table_name is the name of the table you're querying.
  • condition is an optional condition to filter the rows before grouping.

For example, suppose you have a table named sales with columns product and amount, and you want to find the total sales for each product:


SELECT product, SUM(amount) AS total_sales
FROM sales
GROUP BY product;

 

This will give you a result where each row represents a unique product along with its total sales.