SQL - GROUP BY Function



SQL Tutorial - SQL GROUP BY Function


The GROUP BY clause in SQL Server is used to arrange identical data into groups.

The GROUP BY clause always follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

SQL GROUP BY Syntax:


The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2
FROM tablename
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

GROUP BY Example


The Products table has the following records.

ProductID ProductName ProductPrice
Prd001 Pen 40.25
Prd002 Pen 100.75
Prd003 Eraser 10.35
Prd004 Pencil 20.45
Prd005 Book 50.65
Prd006 Gum 25.22

To know the total of the ProductPrice under each Product, the GROUP BY clause can be used as shown below.

SELECT ProductName, SUM (ProductPrice) as TotalPrice
FROM
Products
GROUP BY ProductName

ProductName TotalPrice
Book 50.65
Eraser 10.35
Gum 25.22
Pen 141.00
Pencil 20.45