MySQL SQL

MySQL GROUP BY

The MySQL GROUP BY Statement

Rows with identical values are grouped together into summary rows using the GROUP BY command, as in “find the number of customers in each country”.

To group the result-set by one or more columns, the GROUP BY statement is frequently used in conjunction with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()).

GROUP BY Syntax

				
					SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
				
			

Demo Database

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

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1

Alfreds 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
4

Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22Sweden

MySQL GROUP BY Examples

The quantity of clients in every nation is listed in the SQL statement that follows:

Example

				
					SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
				
			

The following SQL statement lists the number of customers in each country, sorted high to low:

Example

				
					SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
				
			

Demo Database

A sample from the “Orders” table in the Northwind sample database is shown below:

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 amount of orders that each shipper has sent is listed in the SQL statement that follows:

Example

				
					SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
				
			
Share this Doc

MySQL GROUP BY

Or copy link

Explore Topic