SQL Aggregate Functions
On this page
SQL Aggregate Functions
Aggregate functions perform calculations on a set of rows and return a single value. They are commonly used for reporting and data analysis.
Common Aggregate Functions
- COUNT() – returns the number of rows
- SUM() – returns the total of a numeric column
- AVG() – returns the average value
- MIN() – returns the smallest value
- MAX() – returns the largest value
COUNT Example
SELECT COUNT(*) AS total_customers FROM customers;
SUM Example
SELECT SUM(price) AS total_revenue FROM orders;
AVG Example
SELECT AVG(price) AS average_price FROM products;
MIN and MAX Example
SELECT MIN(price) AS lowest_price,
MAX(price) AS highest_price
FROM products;
Aggregate Functions and NULL
Most aggregate functions ignore NULL values. For example, AVG() does not count NULL values in its calculation.
Using WHERE with Aggregates
You can filter rows before aggregation using WHERE.
SELECT COUNT(*) AS active_customers FROM customers WHERE status = 'active';
Grouping Data
To calculate aggregates per category, country, or group, use GROUP BY (covered in detail later).
SELECT country, COUNT(*) AS total_customers FROM customers GROUP BY country;
Common Mistakes
- Forgetting GROUP BY when selecting non-aggregated columns
- Misunderstanding how NULL values affect results
- Using COUNT(column) vs COUNT(*) without knowing the difference
Next Step
Continue with SQL MIN and MAX for a deeper look at value comparison functions.