The GROUP BY statement groups rows that have the same values into summary rows — for example total quantity, average salary, or count of employees. It is commonly used with aggregate functions such as COUNT(), SUM(), AVG(), MAX(), and MIN().
SUM(), AVG(), COUNT() operate on groups.
// Syntax: group rows by one or more columns and apply aggregate functions
SELECT column1, column2, AGGREGATE_FUNCTION(column)
FROM table
GROUP BY column1, column2;
// Example: total sales per category and average salary per department
-- Get the total sales for each product category
SELECT category, SUM(sales)
FROM products
GROUP BY category;
-- Get the average salary by department
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
// Example: group by multiple columns and filter groups using HAVING
SELECT product_id, region, SUM(sales) AS total_sales
FROM sales
GROUP BY product_id, region
HAVING SUM(sales) > 1000;
When you run a GROUP BY query the database scans rows, groups them by the listed column(s), then computes the aggregate(s) for each group. For example, SUM(sales) yields one summed value per distinct category.
For SELECT category, SUM(sales) FROM products GROUP BY category; you might get:
Electronics — 120000Clothing — 54000Home — 78000SELECT in the GROUP BY clause.HAVING to filter aggregated results (e.g., groups with SUM > threshold).SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id;MAX() and MIN().product and region, then filter groups using HAVING.