Skip to main content
SQL Fundamentals
CHAPTER 12 Beginner

SQL Aggregate Functions | COUNT, SUM, AVG, MIN, MAX

Updated: May 16, 2026
15 min read

# CHAPTER 12

Aggregate Functions in SQL

1. Introduction

Thus far, every SELECT query we have written operates on an individual, row-by-row basis. If you ask for prices, SQL hands you a massive list of prices. But what if you don't want the raw data? What if you want the *answers*? You want the Total Revenue, the Average Age, or the Number of Users online. To process massive datasets into a single, summarized mathematical answer, we use Aggregate Functions. In this chapter, we step into the world of Data Analytics.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the concept of data aggregation.
  • Count rows and occurrences using COUNT().
  • Calculate totals using SUM().
  • Find mathematical averages using AVG().
  • Extract the smallest and largest values using MIN() and MAX().

3. The COUNT() Function

The most frequently used aggregate function. It simply counts the number of rows that match your query. If you use COUNT(*), it counts every single row in the table, regardless of what data is inside.
sql
123456
-- Find out EXACTLY how many users exist in the massive database
SELECT COUNT(*) FROM users;

-- Find out how many specific users live in Texas
SELECT COUNT(*) FROM users 
WHERE state = 'TX';

*(Result: Instead of returning 5,000 rows of Texas users, it returns a single row with the number 5000!)*

4. The SUM() Function

If you are running an E-commerce store, COUNT() tells you *how many* items were sold. But SUM() tells you *how much money* you made. SUM() adds up all the numeric values in a specific column.
sql
123
-- Calculate the total gross revenue of all completed orders
SELECT SUM(total_price) FROM orders 
WHERE status = 'Completed';

5. The AVG() Function

The AVG() function adds up all the values in a column and divides by the total number of rows, providing the mathematical mean.
sql
123
-- Find the average salary of employees in the IT department
SELECT AVG(salary) FROM employees 
WHERE department = 'IT';

*(Tip: AVG() often returns crazy decimals like 55400.333333. You can wrap it in a ROUND() function to clean it up! e.g., ROUND(AVG(salary), 2)).*

6. The MIN() and MAX() Functions

These functions scan an entire column and extract the absolute lowest (MIN) or absolute highest (MAX) value. They work on Numbers, Dates, and even Strings (Alphabetically).
sql
12345
-- Find the price of the cheapest product we sell
SELECT MIN(price) FROM products;

-- Find the date of the most recently placed order (Highest Date)
SELECT MAX(order_date) FROM orders;

7. Combining Aggregate Functions (The Dashboard Query)

You can place multiple aggregate functions inside a single SELECT statement to generate a complete business intelligence report in milliseconds.
sql
12345678
-- Generate a complete executive summary report for 2023!
SELECT 
    COUNT(*) AS 'Total Orders Placed',
    SUM(total_price) AS 'Gross Revenue',
    AVG(total_price) AS 'Average Order Value',
    MAX(total_price) AS 'Biggest Sale'
FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';

8. The Danger of Mixing Aggregates with Raw Columns

There is a massive, critical rule in SQL: You cannot mix Aggregate Functions with raw columns unless you are Grouping them.

*Crash Example:* SELECT firstname, COUNT(*) FROM users; Think about it logically. COUNT(*) returns a single number (e.g., 5000). But firstname returns 5,000 separate names. SQL cannot squish 5,000 names into a single row. The database will throw a fatal syntax error.

9. Mini Project: Sales Analytics

Let's analyze the inventory table.
sql
1234567
-- 1. How many total distinct categories of products do we sell?
SELECT COUNT(DISTINCT category) FROM inventory;

-- 2. What is the total dollar value of all inventory sitting in the warehouse?
-- (SQL can do math INSIDE the SUM function!)
SELECT SUM(price * stock_quantity) AS 'Total Asset Value' 
FROM inventory;

10. Common Mistakes

  • COUNT(column) vs COUNT(*): COUNT(*) counts rows. COUNT(email) counts *how many rows have an email address*. If 10 users exist, but 2 have NULL emails, COUNT(*) returns 10, but COUNT(email) returns 8! Aggregate functions (except COUNT(*)) completely ignore NULL values.

11. Best Practices

  • Alias Everything: Aggregate function outputs have extremely ugly column names by default (e.g., SUM(price*qty)). Always use AS 'Clean Name' to format the output for the backend developers who have to read your JSON data.

12. Exercises

  1. 1. What function is used to calculate the total mathematical sum of a numerical column?
  1. 2. Why will the query SELECT username, MAX(score) FROM players; fail to execute in standard SQL?

13. SQL Challenges

Write a single query to analyze the properties table for a real estate firm. Calculate the Total number of active listings (COUNT), the Lowest price (MIN), and the Highest price (MAX). Ensure the property status is 'Active'. Use Aliases for all outputs.
sql
123456
SELECT 
    COUNT(*) AS 'Active Listings',
    MIN(price) AS 'Lowest Price',
    MAX(price) AS 'Highest Price'
FROM properties
WHERE status = 'Active';

14. MCQ Quiz with Answers

Question 1

What is the primary functional difference between COUNT(*) and COUNT(phonenumber) in an SQL query?

Question 2

Why is the SQL statement SELECT firstname, SUM(salary) FROM employees; architecturally invalid?

15. Interview Questions

  • Q: An executive asks for the Average Sales Value. You write SELECT AVG(saleamount) FROM sales;. However, 100 sales records were entered incorrectly with NULL sale amounts. Explain how the AVG() function handles these NULL values mathematically. Does it treat them as zeros, or ignore them entirely?
  • Q: Explain the fatal logic error in attempting to mix raw dimensional columns with aggregate functions in the SELECT statement.

16. FAQs

Q: Are aggregate functions slow on massive tables? A: Yes, if the table has millions of rows, running SUM() requires the database engine to scan every single row and do math. To optimize this, massive enterprise applications often calculate the sum once a night and store it in a separate "reporting" table.

17. Summary

You are now an analyst. By wielding the Big Five aggregate functions—COUNT, SUM, AVG, MIN, and MAX—you can condense millions of rows of chaotic raw data into singular, actionable points of business intelligence.

18. Next Chapter Recommendation

We know how to calculate the Total Revenue of the entire company. But what if the CEO wants to see the Total Revenue *broken down by Department*? In Chapter 13: GROUP BY and HAVING Clauses, we will learn how to bucket data into specific categories before running our math.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·