GROUP BY Clause

Overview

The GROUP BY clause groups rows that have the same values in specified columns into summary rows, like finding the total or average. It is often used with aggregate functions (COUNT, SUM, AVG, MAX, MIN) to produce aggregated results.

Syntax

SELECT column1, column2, aggregate_function(column3)
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING aggregate_condition
ORDER BY column1;

Example

Get the total sales per salesperson from the Sales table.

SELECT SalesPersonID, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY SalesPersonID
ORDER BY TotalSales DESC;

Using HAVING

The HAVING clause filters groups after aggregation.

SELECT Category, COUNT(*) AS ProductCount
FROM Products
GROUP BY Category
HAVING COUNT(*) > 10;