Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
MySQL Group By Clause
Next article icon

MySQL Group By Clause

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In MySQL, the GROUP BY clause is a powerful tool for grouping rows with the same values into summary rows, enabling efficient data analysis. It is often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data.

In this article, We will learn about the MySQL Group By Clause by the understanding with the various aggregate functions examples and so on.

MySQL Group By Clause

  • In MySQL, the GROUP BY clause is useful operator that is used to group rows that have the same values, and can be used to push these values into summary rows, like "find the number of customers in each city" or "calculate the total number of sales per product category."
  • It is often used along with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data.

Syntax:

The GROUP BY clause is used to group rows that have the same values into summary rows. It operates on a set of columns that are specified in the SQL query. The basic syntax involving the GROUP BY operation is given below:

SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;

Where,

  • column1: Columns by which you want to group the result set.
  • aggregate_function: Functions like SUM, COUNT, AVG, etc., to perform calculations on the grouped data.
  • table_name: The table name from which you are fetching the data.
  • condition: Conditions to filter rows before grouping. This is optional if you are giong to perform just a raw and simple query

Examples of MySQL Group By Clause

Before we get into exploring the GROUP BY Clause , we shall see the details of the employees table that we are going to use for our understanding.

Groupby-table

Example 1: Grouping by a Single Column

Lets say that you have a table named employees with column such as customer_id, order_date, and total_amount. We want to find the average salary obtained by each department( such as IT, HR, Marketing etc).

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

Output:

Screenshot-2024-07-21-162409
FIG: Query Result showing the average salary of each dept. grouped by a single column

This query will group rows from the orders table by customer_id and calculate the sum of total_amount for each customer. The result will show each customer_id alongside the total amount they have spent.

Thus by executing the above query , we can find out the average salary that each department employees recieve, and amoung them the finance department marks to have the highest average.

Example 2: Grouping by Multiple Columns

Consider a same employees table ,where this time we will find the average_salary of each employee and retrive the result along with the department they work in.

The query finds the average_salary and returns the tables with the department and the name of the employee along with the average salary.

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

Output:

s2
Fig: Query result showing the grouping by multiple column approch.

This query groups rows from the sales table by both product_id and sale_date. It calculates the sum of quantity for each combination of product_id and sale_date. The result will include each product_id, sale_date pair with the total quantity sold.
Lets see the working of GROUP BY Clause along with the aggregate functions such as SUM, AVG,COUNT,MIN and MAX.

Example 3: MySQL GROUP BY Clause with COUNT Function

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

Output:

s3
Fig: Query result showing the employee count in each department

This query above counts the number of employees in each department, which is performed by COUNT aggregation function.

Example 4: MySQL GROUP BY Clause with SUM Function

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

Output:

s4
Fig: Query result showing the tatal salary of each department

This query sums the salaries of employees in each department using the SUM Aggregate function which does the latter job.

Example 5: MySQL GROUP BY Clause with MIN Function

SELECT department, MIN(salary) AS min_salary
FROM employees
GROUP BY department;

Output:

s6
Fig: Query result showing the minimum salary in each department

This query finds the minimum salary in each department, by making use of the MIN aggregate function available in SQL.

Example 6: MySQL GROUP BY Clause with MAX Function

SELECT department, MAX(salary) AS max_salary
FROM employees
GROUP BY department;

Output:

s7
FIg: Query result showing maximum salary of each department

This query finds the maximum salary in each department, which is executed by the use of MAX as the aggregate function.

Example 7: MySQL GROUP BY Clause with AVG Function

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

Output:

s8
Fig: Query result showing the average salary of each department

This query calculates the average salary in each department, which is performed by the AVG Function as the aggregation.

Conclusion

Overall, GROUP BY clause in MySQL is an essential tool for data analysis and reporting. It allows you to group rows that have the same values into summary rows and perform calculations on these groups using aggregate functions like SUM, COUNT, AVG, MIN, and MAX. By mastering the GROUP BY clause, you can efficiently analyze and summarize large datasets, making it an invaluable skill for any database professional or data analyst.


Next Article
MySQL Group By Clause

T

tmpravi5i5j
Improve
Article Tags :
  • Databases
  • MySQL

Similar Reads

    SQLite Group By Clause
    SQLite is a server-less database engine and it is written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we
    6 min read
    PL/SQL GROUP BY Clause
    The GROUP BY clause in PL/SQL is a powerful tool used to organize data into aggregated groups based on one or more columns. It is essential for performing summary operations on large datasets, enabling efficient data analysis by grouping rows that share common values.In this article, We will learn a
    7 min read
    PostgreSQL - GROUP BY clause
    The GROUP BY clause in PostgreSQL is an essential tool that allows us to group rows that share the same values in one or more columns. This powerful functionality is commonly used to perform aggregate calculations such as SUM(), COUNT(), AVG(), and more, enabling us to summarize data efficiently. In
    4 min read
    MariaDB GROUP BY Clause
    An important feature in MariaDB, and SQL in general, is the GROUP BY clause. This article explains the important features of the GROUP BY clause in MariaDB. This article explains you the syntax of the GROUP BY clause and its practical applications. Examples include using the aggregate functions, gro
    6 min read
    SQL COUNT() with GROUP BY Clause
    The SQL COUNT() function is a powerful tool used to count the number of rows in a dataset. When combined with the GROUP BY clause, it helps group data by specific attributes and count rows within each group. This is particularly useful for summarising data and generating insights.In this article, we
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences