Table results can be grouped. They are always grouped by at least one table column. If you want you can group by multiple columns.

The results of a SELECT query can be grouped using the GROUP BY query.

You may like:
Learning SQL: Master SQL Fundamentals

GROUP by

Setup table

If you do not have a table with data, create it first. In this example we define a table named students with several columns: id, gender, firstname, lastname and student id.

The SQL query we use to do that is:

1
2
3
4
5
6
7
 
sql> CREATE DATABASE exampleDb;
sql> USE exampleDb;
sql> CREATE TABLE Students ( PersonID int, Gender int, LastName varchar(255), FirstName varchar(255), StudentID int );
sql> INSERT INTO Students VALUES ( 13148, 0, 'Johnson', 'John', 6391931);
sql> INSERT INTO Students VALUES ( 13149, 1, 'Dylan', 'Abby', 439225);
sql> INSERT INTO Students VALUES ( 13149, 1, 'Hinton', 'Alice', 139225);

Syntax

The GROUP BY clause syntax is written in this style:

1
SELECT .. FROM table GROUP BY ...

Example

Then we can group results by gender:

1
2
3
4
5
6
7
sql> SELECT Gender, COUNT(*) FROM Students GROUP BY Gender;
+--------+----------+
| Gender | COUNT(*) |
+--------+----------+
| 0 | 1 |
| 1 | 2 |
+--------+----------+