Site icon TestingDocs.com

MySQL GROUP BY Clause

Overview

In this tutorial, we will learn about the MySQL GROUP BY Clause. A GROUP BY clause can be used based on the values in one or more columns of the selected group of rows.

MySQL GROUP BY Clause

A GROUP BY clause places selected rows into groups. Grouping is useful when we use aggregate functions. With a GROUP BY clause, an aggregate function calculates a summary value for each group.

Without a GROUP BY clause MySQL treats all the selected rows as a single group. The Aggregate function without GROUP BY clause calculates the result based on the entire set of rows.

For example, if a WHERE clause selects 15 rows and the GROUP BY arranges them into three groups of five rows each, an aggregate function produces the result for each of the three groups.

Example

For example, Let’s take the Country table from the MySQL world database. We can group the rows by Continent and calculate the sum population of countries in each continent.

mysql> SELECT Continent, SUM(Population)
-> FROM Country
-> GROUP BY Continent ;

+—————+—————–+
| Continent | SUM(Population) |
+—————+—————–+
| North America | 482993000 |
| Asia | 3705025700 |
| Africa | 784475000 |
| Europe | 730074600 |
| South America | 345780000 |
| Oceania | 30401150 |
| Antarctica | 0 |
+—————+—————–+
7 rows in set (0.01 sec)

 

 

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

 

Exit mobile version