How To Use Group By In Sql in SQL
How to Use GROUP BY in SQL
The GROUP BY clause is used to group rows that have the same values in specified columns into summary rows, like to calculate aggregates (SUM, COUNT, AVG, etc.) for each group.
Syntax:
SELECT column1, aggregate_function(column2)FROM table_nameGROUP BY column1;Example:
Suppose you have a table sales with columns: region, sales_amount.
To get the total sales per region:
SELECT region, SUM(sales_amount) AS total_salesFROM salesGROUP BY region;How it works:
Rows with the same
regionare grouped together.The
SUMcalculates the total sales for each region.You can use other aggregate functions like
COUNT(),AVG(),MAX(),MIN().
Important Notes:
Columns in the
SELECTlist must be either in theGROUP BYclause or inside aggregate functions.You can group by multiple columns:
SELECT region, product_category, COUNT(*) AS total_ordersFROM salesGROUP BY region, product_category;If you want examples with HAVING or other advanced use, just ask!