SQL — Group By
Basic GROUP BY
SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department;
Multiple columns
SELECT department, status, COUNT(*) AS count
FROM employees
GROUP BY department, status;
GROUP BY with HAVING
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
Aggregate functions
SELECT
department,
COUNT(*) AS total,
AVG(salary) AS avg_salary,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary,
SUM(salary) AS total_salary
FROM employees
GROUP BY department;
GROUP BY with ROLLUP
SELECT department, status, COUNT(*)
FROM employees
GROUP BY ROLLUP(department, status);
GROUP BY with CUBE
SELECT department, status, COUNT(*)
FROM employees
GROUP BY CUBE(department, status);
Mini Practice
Write SQL code that:
- Groups by a single column
- Uses HAVING to filter groups
- Uses multiple aggregate functions
- Demonstrates ROLLUP
Up Next
In the next lesson, you'll learn about Subqueries — queries within queries.
Related Topics
Frequently Asked Questions about Group By
What is Group By in SQL?
Group By is a fundamental concept in SQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Group By?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Group By.
Why is Group By important in SQL?
Group By is essential for SQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.