bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL GROUP BY Statement

The SQL GROUP BY Statement

The GROUP BY statement is used to group rows that have the same values into summary rows, like "Find the number of customers in each country".

The GROUP BY statement is almost always used in conjunction with aggregate functions, like COUNT() , MAX() , MIN() , SUM() , AVG() , to perform calculations on each group.

GROUP BY Syntax

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

Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

Demo Database

Below is a selection from the "Orders" table in the Northwind sample database:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
102489051996-07-043
102498161996-07-051
102503441996-07-082

And a selection from the "Shippers" table:

ShipperIDShipperName
1Speedy Express
2United Package
3Federal Shipping

GROUP BY With JOIN Example

The following SQL returns the number of orders sent by each shipper:

Example

  SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM
  Orders
LEFT JOIN Shippers
ON Orders.ShipperID = Shippers.ShipperID

  GROUP BY ShipperName;

Previous

SQL UNION ALL Operator

Next

SQL HAVING Clause