Aggregate Functions in SQL - Detailed Guide
Introduction
Aggregate functions are an essential part of database management systems. They allow users to
perform calculations on a set of values and return a single summarized result. These functions are
widely used in SQL queries for reporting, data analysis, and decision-making processes.
Definition
An aggregate function processes multiple rows of a table and returns a single value. It ignores NULL
values (except COUNT(*)) and is often used with GROUP BY and HAVING clauses.
Example Table: Student Marks
Name Marks
A 80
B 90
C 70
D 85
Types of Aggregate Functions
1. COUNT(): Counts number of rows. Example: SELECT COUNT(*) FROM students; 2. SUM():
Returns total sum. Example: SELECT SUM(marks) FROM students; 3. AVG(): Returns average value.
Example: SELECT AVG(marks) FROM students; 4. MIN(): Returns minimum value. Example: SELECT
MIN(marks) FROM students; 5. MAX(): Returns maximum value. Example: SELECT MAX(marks)
FROM students;
GROUP BY Clause
The GROUP BY clause is used with aggregate functions to group rows with similar values. Example:
SELECT department, AVG(salary) FROM employees GROUP BY department;
HAVING Clause
The HAVING clause is used to filter groups created by GROUP BY. Example: SELECT department,
AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;
Real-World Use Cases
1 Finding total sales of a company
2 Calculating average marks of students
3 Finding highest salary in a department
4 Counting number of users
5 Analyzing business reports
Advantages
1 Simplifies data analysis
2 Reduces complexity
3 Provides summarized insights
4 Improves performance
Conclusion
Aggregate functions are powerful tools in SQL that help transform raw data into meaningful information.
They are widely used in real-world applications and are crucial for anyone working with databases.