bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/SQL/SQL Tutorial
SQL•SQL Tutorial

SQL GROUP BY Statement

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind SQL GROUP BY Statement?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___, aggregate_function(column2), column3, ...
3Order

Put the learning moves in the order that makes the concept easiest to apply.

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".
GROUP BY With JOIN Example
The 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