SQL - Group By Clause

This tutorial will explain how to use GROUP BY clause in a SQL query and how to use them with the examples.

GROUP BY clause is used to group the results by given column name(s)

This is the general statement to use GROUP BY from a table

SELECT
column1, column2, ...
FROM
tablename
GROUP BY
column1,
column2,
...

Lets create a sample table and add some rows

CREATE TABLE SampleContacts (
FullName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL,
Age INT NOT NULL
);


INSERT INTO SampleContacts
(FullName, Gender, Age)
VALUES
('Contact1', 'M', 26),
('Contact2', 'M', 29),
('Contact3', 'F', 27),
('Contact4', 'F', 29),
('Contact5', 'F', 27),
('Contact6', 'M', 29)

A) Using GROUP BY clause with single column
The following statement returns all gender values via removing any duplicates from SampleContacts table:

SELECT
Age
FROM
SampleContacts
GROUP BY
Age

| Gender |
----------
      M
      F

If GROUP BY clause was not used, it would return 6 records instead of 2. It basicly displays the unique value via removing duplicates.

B) Using GROUP BY clause with multiple columns
The following statement returns all gender values via removing any duplicates from SampleContacts table:

SELECT
Gender, Age
FROM
SampleContacts
GROUP BY
Gender, Age

| Gender | Age |
------------------
       F        27
       F        29
       M       26
       M       29

This time uniqueness defined with the combination of the given multiple columns