Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sql
count
group by

How to use SQL COUNT GROUP BY

Educative Answers Team

GROUP BY is a SQL command used to merge similar set of data under one field. A user can merge this data according to the field of his/her own choice. A GROUP BY returns one record for each group.

COUNT is a command which counts the number of records present in a particular field.

In the illustration below there is a blue circle, some green circles, and a few purple circles; each circle has a particular hexagon attached to them. The GROUP BY function is called to group the hexagons according to the circles they are attached with. Later, the COUNT function is used to count the number of hexagons attached with a particular circle.

svg viewer

Example

Suppose there is a table which stores the records of immigrants. It stores their names, IDs and nationality.

Table : Immigrants

ID Name Country
123 Rooney England
457 Nekham Australia
312 George USA
761 McKenzie USA
478 McGrath Australia
567 Mukesh India
978 John USA
445 Angelina USA
771 Mark Russia
414 Peter England

Now, if this table is grouped by nationality and their IDs are to be counted and displayed, the code will be :

SELECT COUNT(id), nationality 
  FROM immigrants
 GROUP BY(nationality)

The above code correctly calculates the number of people belonging to each specific country.

RELATED TAGS

sql
count
group by
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring