GROUP BY Clause in SQL
SQL GROUP BY tutorial with examples and explanations
The GROUP BY clause in SQL is used to group rows that have the same values in one or more columns. It is commonly used with aggregate functions like COUNT(), SUM(), AVG(), MIN(), and MAX().
In this beginner-friendly SQL tutorial, you will learn:
What GROUP BY is
How GROUP BY works
Syntax and examples
GROUP BY with aggregate functions
GROUP BY with multiple columns
HAVING vs WHERE
Real-world use cases
Best practices
The GROUP BY clause groups rows that have the same value in a column into summary rows.
GROUP BY is mainly used to:
Generate summarized reports
Count records by category
Calculate totals and averages
Categorize data by groups
Example outputs include:
Number of employees per department
Total sales per product
Average salary per city
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
| id | name | department | salary |
|---|---|---|---|
| 1 | Amit | IT | 50000 |
| 2 | Neha | HR | 45000 |
| 3 | Rahul | IT | 60000 |
| 4 | Sara | HR | 55000 |
| 5 | Karan | Finance | 70000 |
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
| department | total_employees |
|---|---|
| IT | 2 |
| HR | 2 |
| Finance | 1 |
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
You can group by more than one column.
SELECT department, city, COUNT(*) AS total
FROM employees
GROUP BY department, city;
The HAVING clause filters grouped results.
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING total_salary > 100000;
| Feature | WHERE | HAVING |
|---|---|---|
| Filters rows before grouping | β | β |
| Filters rows after grouping | β | β |
| Can use aggregate functions | β | β |
Filter IT department before grouping:
SELECT department, COUNT(*)
FROM employees
WHERE department = 'IT'
GROUP BY department;
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id;
SELECT product_name, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_name;
SELECT city, COUNT(*)
FROM users
GROUP BY city;
β Use meaningful aliases (AS total_salary, AS count)
β Always pair GROUP BY with an aggregate function
β Ensure grouped columns exist in SELECT
β Use HAVING for filtered aggregated results
β Index grouping columns for performance
In this SQL GROUP BY tutorial, you learned:
How GROUP BY groups rows with common values
How to use aggregate functions (COUNT, SUM, AVG)
How HAVING filters grouped results
Real-world examples and best practices
The GROUP BY clause is essential for reporting, analytics, and summarizing large datasets.