SQL aggregate functions enable developers to perform basic calculations across multiple rows in a database, answering questions like "how many," "what's the highest," or "what's the average value." In this tutorial, you will learn how to:
MAX, MIN, and COUNT.GROUP BY and filter grouped results with HAVING.Aggregate functions allow you to perform calculations on a set of rows. The most commonly used functions include:
COUNT: Counts the number of rows.MIN: Finds the smallest value.MAX: Finds the largest value.SUM or TOTAL: Adds up all values.AVG: Calculates the average of values.Always check your database's documentation to ensure the correct usage of aggregate functions. For SQLite, refer to the SQLite Aggregate Functions.
You can include aggregate functions directly in a SELECT clause. For example:
SELECT COUNT(*) AS count
FROM employees;
SELECT MAX(commission) AS highest_commission
FROM commissions;
To calculate aggregates on a subset of rows, use a WHERE clause:
SELECT COUNT(*) AS count
FROM employees
WHERE department = 'Sales';
The GROUP BY clause groups rows based on a column and performs aggregate calculations for each group.
SELECT COUNT(id) AS employee_count, city
FROM employee_addresses
GROUP BY city;
SELECT AVG(sales_amount) AS avg_sales, month, year
FROM sales
GROUP BY month, year;
You can order query results based on aggregate values using the ORDER BY clause.
SELECT COUNT(order_id) AS order_count, city, state
FROM orders
GROUP BY city, state
ORDER BY order_count DESC;
SELECT city, state
FROM orders
GROUP BY city, state
ORDER BY COUNT(order_id) DESC
LIMIT 1;
Use HAVING to filter grouped data based on aggregate values. Unlike WHERE, which filters rows before grouping, HAVING filters groups after aggregation.
Return cities with more than one order:
SELECT COUNT(order_id) AS order_count, city, state
FROM orders
GROUP BY city, state
HAVING order_count > 1
ORDER BY order_count DESC;
SQL aggregate functions are essential in scenarios such as:
In this lesson, you learned:
COUNT, MIN, MAX, SUM, and AVG.GROUP BY and filter grouped results using HAVING.ORDER BY.By combining these techniques, you can perform advanced data analysis and generate insightful reports directly from your database.