Aggregate Functions
Aggregate Functions
Definition: Aggregate functions perform a calculation on a set of values and return a single, summarizing value. Instead of looking at individual rows, these functions look at the "big picture" of your data.
Learning Outcome: Mastering aggregate functions like SUM, AVG, and COUNT is a core requirement for data analysis. These tools allow you to transform raw data into meaningful reports, such as calculating total sales, finding average test scores, or counting the number of registered users.
Common Aggregate Functions
SQL provides several built-in functions to handle numerical and descriptive statistics:
| Function | Description | Example Usage |
|---|---|---|
COUNT() |
Counts the total number of rows or non-null values. | COUNT(*) to see total students. |
SUM() |
Calculates the total sum of a numeric column. | SUM(marks) to get total class points. |
AVG() |
Returns the average value of a numeric column. | AVG(age) to find the mean age. |
MIN() |
Finds the smallest value in the column. | MIN(age) to find the youngest student. |
MAX() |
Finds the largest value in the column. | MAX(marks) to find the highest score. |
Examples: Basic Calculations
To count how many total students are currently in your table:
SELECT COUNT(*) FROM students;
To calculate the average age of all students in the database:
SELECT AVG(age) FROM students;
Key Notes
- Null Values: Most aggregate functions (except
COUNT(*)) ignoreNULLvalues in their calculations. For example,AVGwill only average rows that actually contain a number. - Single Value Output: Remember that a query using an aggregate function without a
GROUP BYclause will always return exactly one row as the result. - Aliasing: It is common practice to use
ASto give your result a cleaner name, such asSELECT AVG(age) AS average_student_age. - Data Types: Functions like
SUMandAVGonly work on numeric data types (INT, DECIMAL, etc.), whileCOUNT,MIN, andMAXcan work on text and dates as well.
🏋️ Test Yourself With Exercises
Take our quiz on Aggregate Functions to test your knowledge.
Browse Quizzes »