Learn COUNT, SUM, AVG, MIN, MAX for Beginners
Master SQL aggregate functions and grouping in this beginner-friendly tutorial. Learn to use COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING clauses to summarize and analyze data. Practice counting employees per department, calculating average salaries, and finding departments with maximum or minimum salaries.
1. Introduction
Aggregate functions in SQL allow you to perform calculations on multiple rows of data and return a single summarized value. Combined with grouping, they are essential for reporting and analytics.
Key Points:
- Aggregate functions summarize data.
- GROUP BY groups rows with the same values into summary rows.
- HAVING filters grouped data, unlike WHERE which filters individual rows.
2. Aggregate Functions
| FunctionDescriptionExample | ||
| COUNT() | Counts rows | COUNT(*) counts all rows in a table |
| SUM() | Adds values | SUM(Salary) |
| AVG() | Calculates average | AVG(Salary) |
| MIN() | Finds minimum | MIN(Salary) |
| MAX() | Finds maximum | MAX(Salary) |
Examples:
3. GROUP BY Clause
GROUP BY groups rows with the same values in one or more columns.
Syntax:
Examples:
4. HAVING Clause
HAVING filters the grouped results, similar to WHERE but for groups.
Syntax:
Examples:
5. Practical Exercises
- Count employees per department.
- Calculate the average salary per department.
- Find departments with maximum and minimum salaries.
- List departments with more than 5 employees using HAVING.
- Find departments where the total salary exceeds 300000.
6. Tips for Beginners
- Use COUNT() to quickly know the number of rows.
- Use GROUP BY with aggregate functions for summary reports.
- Use HAVING to filter groups after aggregation.
- Avoid using WHERE with aggregate functions; HAVING is used instead.
Next Step: After mastering aggregate functions and grouping, the next module is Joins and Relationships, where you’ll learn INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN, and self-joins for combining data from multiple tables.