The GROUP BY
statement groups rows with common values into summary rows. It is typically used with aggregate functions like COUNT()
, SUM()
, AVG()
, MIN()
, and MAX()
.
SQL Group By Syntax
SQL
x
1
SELECT column_name(s)
2
FROM table_name
3
WHERE condition
4
GROUP BY column_name(s)
5
ORDER BY column_name(s);
SQL Group By Example
Count patients by gender:
Using the Patients
table, we can count how many patients belong to each gender.
SQL
1
1
SELECT gender, COUNT(patient_id) AS total_patients
2
FROM Patients
3
GROUP BY gender;

Count medical records per patient:
This retrieves the number of medical records associated with each patient.
SQL
1
1
SELECT patient_id, COUNT(record_id) AS total_records
2
FROM MedicalRecords
3
GROUP BY patient_id;

SQL GROUP BY with JOIN Example
Count appointments per doctor:
To analyze appointment counts for each doctor, we join the Appointments
and Doctors
tables:
SQL
1
1
SELECT Doctors.first_name || ' ' || Doctors.last_name AS doctor_name, COUNT(Appointments.appointment_id) AS total_appointments
2
FROM Appointments
3
LEFT JOIN Doctors ON Appointments.doctor_id = Doctors.doctor_id
4
GROUP BY doctor_name;

SQL Group By Visual Diagram
