Preloader

GROUP BY Clause in SQL

SQL
SQL Tutorials

The GROUP BY clause in SQL groups rows that share the same values. It is mainly used with aggregate functions such as COUNT, SUM, AVG, MIN, and MAX.

Because of this, GROUP BY helps you summarize data instead of viewing every single row.

Why GROUP BY Clause in SQL Is Used

GROUP BY is useful when you want to
combine similar data
generate summary reports
analyze totals or averages
work with large tables

As a result, it plays an important role in data analysis.

Sample Table Used for GROUP BY

students

id | name | city | marks
1 | Rahul | Delhi | 85
2 | Neha | Mumbai | 92
3 | Amit | Delhi | 78
4 | Priya | Pune | 88
5 | Karan | Mumbai | 90

Basic GROUP BY Example

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

This query counts students in each city.

GROUP BY with SUM

SELECT city, SUM(marks) 
FROM students
GROUP BY city;

This query shows total marks for each city.

GROUP BY with AVG

SELECT city, AVG(marks) 
FROM students
GROUP BY city;

This query calculates average marks per city.

GROUP BY with Multiple Columns

SELECT city, name, AVG(marks)
FROM students
GROUP BY city, name;

This groups data by both city and name.

GROUP BY Clause with WHERE

SELECT city, COUNT(*) 
FROM students
WHERE marks > 80
GROUP BY city;

This filters data first and then groups it.

Important Rule of GROUP BY Clause in SQL

Every column in the SELECT list must either
be part of GROUP BY
or use an aggregate function

Ignoring this rule causes errors.

Common Mistake Example

SELECT city, name, AVG(marks)
FROM students
GROUP BY city;

This query fails because name is not grouped.

Real World Use Cases

GROUP BY clause in SQL is commonly used in
sales reports
student performance analysis
banking summaries
inventory tracking

Summary

GROUP BY groups similar rows.
It works with aggregate functions.
It helps summarize large datasets.

Once you understand GROUP BY, reporting becomes much easier.

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *