Group by
Group by
• The GROUP BY clause in SQL is used to arrange identical data into groups. It is typically used with aggregate
functions (like COUNT(), SUM(), AVG(), MAX(), MIN()) to perform operations on each group of data.
1. Data Grouping: When you use GROUP BY, you specify one or more columns that you want to group the
data by. For example, you might want to group students by their grade, meaning all students in the same
grade will be grouped together.
2. Aggregate Functions: Once the data is grouped, you can use aggregate functions to perform calculations on
each group. For example, you can count how many students are in each grade, calculate the average age of
students in each department, or find the highest marks in each city.
Key Concepts
•
GROUP BY Query with Example: students Table
• The GROUP BY clause in SQL is used to arrange identical data into groups, often used with aggregate functions like
COUNT(), SUM(), AVG(), MAX(), and MIN(). Let's walk through an example of using the GROUP BY clause with a
students table.
student_id INT ,
first_name VARCHAR(50),
last_name VARCHAR(50),
grade_level INT,
enrollment_date DATE
);
insert
student_id first_name last_name grade_level score enrollment_date
This query groups students by their department and calculates the average age of students in each
department.
Group by city and find the highest marks in each city
FROM student
GROUP BY city;
This query groups students by their city and finds the highest marks achieved by students in each city.