Lesson 40 of 60 – GROUP BY
67%

GROUP BY in SQL

The GROUP BY clause is used to group rows that have the same values in one or more columns. It is commonly used with aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX().

Note: GROUP BY is useful when you want summary information separately for each category, such as students per course, total sales per product, or average marks per class.

1. What is GROUP BY?

The GROUP BY clause combines rows having the same value into groups.

SELECT course, COUNT(*)
FROM students
GROUP BY course;

This query counts students separately for each course.

2. Why Use GROUP BY?

GROUP BY is used when you need summary information for different categories.

For example:

  • Number of students in each course
  • Total sales for each product
  • Average marks for each class
  • Total salary for each department
  • Number of employees in each department

3. Basic GROUP BY Syntax

The basic syntax is:

SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;

Example:

SELECT course, COUNT(*)
FROM students
GROUP BY course;

4. GROUP BY with COUNT()

COUNT() can be used with GROUP BY to count records in each group.

SELECT course, COUNT(*) AS total_students
FROM students
GROUP BY course;

This shows the number of students in every course.

5. GROUP BY with SUM()

SUM() can calculate a total separately for every group.

SELECT course, SUM(fee) AS total_fee
FROM students
GROUP BY course;

This calculates the total fee for each course.

6. GROUP BY with AVG()

AVG() can calculate the average value for each group.

SELECT course, AVG(marks) AS average_marks
FROM students
GROUP BY course;

This calculates the average marks for each course.

7. GROUP BY with MIN()

MIN() can find the smallest value in each group.

SELECT course, MIN(marks) AS lowest_marks
FROM students
GROUP BY course;

This returns the lowest marks for each course.

8. GROUP BY with MAX()

MAX() can find the largest value in each group.

SELECT course, MAX(marks) AS highest_marks
FROM students
GROUP BY course;

This returns the highest marks for each course.

9. GROUP BY with Multiple Aggregate Functions

You can use several aggregate functions in the same query.

SELECT
    course,
    COUNT(*) AS total_students,
    AVG(marks) AS average_marks,
    MIN(marks) AS lowest_marks,
    MAX(marks) AS highest_marks
FROM students
GROUP BY course;

This generates a complete summary for every course.

10. GROUP BY with WHERE

WHERE filters rows before they are grouped.

SELECT course, COUNT(*) AS total_students
FROM students
WHERE status = 'Active'
GROUP BY course;

This counts only active students in each course.

11. GROUP BY with ORDER BY

ORDER BY can be used after GROUP BY to sort grouped results.

SELECT course, COUNT(*) AS total_students
FROM students
GROUP BY course
ORDER BY total_students DESC;

The courses with more students appear first.

12. GROUP BY Multiple Columns

You can group data using more than one column.

SELECT course, status, COUNT(*) AS total_students
FROM students
GROUP BY course, status;

This creates groups based on the combination of course and status.

13. GROUP BY Two Columns

Multiple columns allow more detailed summaries.

SELECT department, gender, COUNT(*) AS total_employees
FROM employees
GROUP BY department, gender;

This counts employees for each department and gender combination.

14. GROUP BY with DISTINCT Values

GROUP BY naturally produces one result row for each group.

SELECT course
FROM students
GROUP BY course;

This returns each course once.

15. GROUP BY and NULL Values

If the grouped column contains NULL values, those NULL values can form their own group.

SELECT course, COUNT(*) AS total_students
FROM students
GROUP BY course;

A group can therefore represent rows where the course value is NULL.

16. GROUP BY with IN

IN can be used in WHERE before grouping.

SELECT course, COUNT(*) AS total_students
FROM students
WHERE course IN ('Python', 'SQL')
GROUP BY course;

This groups only Python and SQL students.

17. GROUP BY with BETWEEN

BETWEEN can filter records before GROUP BY is applied.

SELECT course, AVG(marks) AS average_marks
FROM students
WHERE marks BETWEEN 50 AND 100
GROUP BY course;

This calculates the average marks for qualifying records in each course.

18. GROUP BY with LIKE

LIKE can be used to filter records before grouping.

SELECT course, COUNT(*) AS total_students
FROM students
WHERE course LIKE 'P%'
GROUP BY course;

This groups courses whose names start with P.

19. GROUP BY with Dates

GROUP BY can be used with date-related columns to summarize records.

SELECT admission_date, COUNT(*) AS total_students
FROM students
GROUP BY admission_date;

This counts students for each admission date.

20. GROUP BY with Year

In MySQL, functions such as YEAR() can be used to group records by year.

SELECT
    YEAR(admission_date) AS admission_year,
    COUNT(*) AS total_students
FROM students
GROUP BY YEAR(admission_date);

This provides the number of students admitted in each year.

21. GROUP BY with Month

You can also group records by month using appropriate date functions.

SELECT
    MONTH(admission_date) AS admission_month,
    COUNT(*) AS total_students
FROM students
GROUP BY MONTH(admission_date);

This counts students for each month number.

22. GROUP BY with Alias

Aliases can make grouped results easier to understand.

SELECT
    course AS course_name,
    COUNT(*) AS student_count
FROM students
GROUP BY course;

The output columns have meaningful names.

23. GROUP BY and Aggregate Results

GROUP BY does not itself calculate totals or averages. Aggregate functions perform the calculations for each group.

SELECT course, COUNT(*)
FROM students
GROUP BY course;

Here, GROUP BY creates the course groups and COUNT() calculates the number of rows in each group.

24. GROUP BY with Payment Data

GROUP BY is very useful for payment reports.

SELECT
    course,
    SUM(amount) AS total_payment
FROM payments
WHERE status = 'Paid'
GROUP BY course;

This calculates paid amounts separately for each course.

25. GROUP BY for Employee Salary

You can calculate salary summaries for each department.

SELECT
    department,
    SUM(salary) AS total_salary,
    AVG(salary) AS average_salary
FROM employees
GROUP BY department;

This shows total and average salary for each department.

26. GROUP BY with COUNT and ORDER BY

Grouped results can be sorted by an aggregate value.

SELECT
    course,
    COUNT(*) AS total_students
FROM students
GROUP BY course
ORDER BY total_students DESC;

This sorts courses from the highest student count to the lowest.

27. Common GROUP BY Mistake

A common mistake is selecting a non-aggregated column that is not properly included in GROUP BY.

SELECT course, name, COUNT(*)
FROM students
GROUP BY course;

Depending on the SQL mode and database system, this query may be invalid or produce an unintended result. When grouping, make sure selected non-aggregated columns are appropriately included in GROUP BY.

28. GROUP BY vs ORDER BY

  • GROUP BY creates groups of similar values.
  • ORDER BY sorts the result.
SELECT course, COUNT(*) AS total_students
FROM students
GROUP BY course
ORDER BY total_students DESC;

Here GROUP BY creates the groups and ORDER BY sorts them.

29. Practical Student Report

A practical student report can show the number of students and average marks for every course.

SELECT
    course,
    COUNT(*) AS total_students,
    AVG(marks) AS average_marks,
    MIN(marks) AS lowest_marks,
    MAX(marks) AS highest_marks
FROM students
GROUP BY course
ORDER BY total_students DESC;

This provides a useful course-wise student performance summary.

30. Complete GROUP BY Example

Here is a complete example using GROUP BY with filtering, aggregate functions, and sorting.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    course VARCHAR(100),
    status VARCHAR(20),
    marks INT,
    fee DECIMAL(10,2)
);

SELECT
    course,
    COUNT(*) AS total_students,
    SUM(fee) AS total_fee,
    AVG(marks) AS average_marks,
    MIN(marks) AS lowest_marks,
    MAX(marks) AS highest_marks
FROM students
WHERE status = 'Active'
GROUP BY course
ORDER BY total_students DESC;

This query creates a course-wise report containing the number of active students, total fees, average marks, lowest marks, and highest marks.

📌 Key Points

  • GROUP BY groups rows with the same values.
  • It is commonly used with aggregate functions.
  • COUNT() can count records in each group.
  • SUM() can calculate totals for each group.
  • AVG() can calculate averages for each group.
  • MIN() and MAX() can find minimum and maximum values in each group.
  • Multiple columns can be used with GROUP BY.
  • WHERE filters rows before GROUP BY.
  • ORDER BY can sort grouped results.
  • GROUP BY is useful for reports and summaries.
  • GROUP BY is commonly used for course-wise, department-wise, product-wise, and date-wise reports.

🧠 Quick Quiz

Question: Which SQL clause is used to group rows with the same values?