Aggregate Functions: Summary Analytics 📊
So far, every query we've written operated on a row-by-row basis: 10 input rows produced up to 10 output rows.
In the real world, businesses and software engineers frequently ask summary questions:
- "How many orders did we process today?"
- "What is our total revenue for the quarter?"
- "What is the average customer rating for product X?"
- "Who has the highest and lowest salary in the company?"
To answer these questions, SQL provides Aggregate Functions (also known as Column Functions or Summary Functions).
Definition: An Aggregate Function performs a mathematical calculation on a set of values across multiple rows and returns a single scalar value.
1. The Core Five Aggregate Functions 🖐️
SQL standards define five fundamental aggregate functions:
| Function | What it Calculates | Data Types Supported |
|---|---|---|
COUNT() | Counts the number of rows or non-NULL values | Any data type |
SUM() | Computes the arithmetic sum of values | Numeric only (INT, DECIMAL, FLOAT) |
AVG() | Computes the arithmetic mean () | Numeric only |
MIN() | Finds the minimum value | Numbers, Dates, Text (alphabetical) |
MAX() | Finds the maximum value | Numbers, Dates, Text (alphabetical) |
2. Our Working Dataset: sales 🛒
Let's use this realistic sales table for our examples:
Table: sales
┌────┬──────────────┬─────────────┬────────┬────────────┬─────────┐
│ id │ customer_id │ product │ amount │ order_date │ coupon │
├────┼──────────────┼─────────────┼────────┼────────────┼─────────┤
│ 1 │ 101 │ Laptop │ 65000 │ 2024-03-01 │ SAVE10 │
│ 2 │ 102 │ Mouse │ 1200 │ 2024-03-02 │ NULL │
│ 3 │ 101 │ Keyboard │ 3500 │ 2024-03-03 │ SAVE10 │
│ 4 │ 103 │ Monitor │ 18000 │ 2024-03-05 │ NULL │
│ 5 │ 104 │ Desk Lamp │ 2300 │ 2024-03-07 │ SPRING │
└────┴──────────────┴─────────────┴────────┴────────────┴─────────┘
3. The Great COUNT(*) vs COUNT(column) Distinction 🎯
One of the most frequent SQL interview questions is: "What is the difference between COUNT(*) and COUNT(column_name)?"
Rule 1: COUNT(*) counts EVERY row
COUNT(*) simply counts physical rows matching your WHERE filter, regardless of whether any columns contain NULL:
SELECT COUNT(*) AS total_ordersFROM sales;Result:5 (Because there are 5 physical rows in the table).
Rule 2: COUNT(column_name) ignores NULL values!
When you pass a specific column name into COUNT, SQL skips and ignores all NULL values:
SELECT COUNT(coupon) AS orders_with_couponsFROM sales;Result:3 (Only rows 1, 3, and 5 have coupons. Rows 2 and 4 have NULL coupons, so they are ignored).
4. SUM() and AVG() 💰
Calculate our total revenue and average transaction size:
SELECT SUM(amount) AS total_revenue, AVG(amount) AS average_order_valueFROM sales;Result:
┌───────────────┬─────────────────────┐
│ total_revenue │ average_order_value │
├───────────────┼─────────────────────┤
│ 90000 │ 18000.00 │
└───────────────┴─────────────────────┘
⚠️ How AVG() Handles NULL Values:
Crucial Rule:
AVG()calculates , NOT.
If an employee has aNULLsalary or rating,AVG()completely excludes that row from both the numerator and the denominator—it does not treat it as zero!
5. MIN() and MAX() Beyond Numbers 📅
MIN and MAX work effortlessly on numbers, but they are equally powerful on dates and strings:
SELECT MIN(order_date) AS first_sale_date, MAX(order_date) AS latest_sale_date, MIN(product) AS first_alphabetical_product, MAX(amount) AS largest_single_orderFROM sales;Result:
┌─────────────────┬──────────────────┬─────────────────────────────┬──────────────────────┐
│ first_sale_date │ latest_sale_date │ first_alphabetical_product │ largest_single_order │
├─────────────────┼──────────────────┼─────────────────────────────┼──────────────────────┤
│ 2024-03-01 │ 2024-03-07 │ Desk Lamp │ 65000 │
└─────────────────┴──────────────────┴─────────────────────────────┴──────────────────────┘
6. Combining Aggregates with DISTINCT ✨
What if customer 101 placed 5 different orders? If you want to know how many unique customers have purchased from you:
-- ❌ Wrong: Counts total orders (including repeat customers)SELECT COUNT(customer_id) FROM sales; -- Returns 5-- ✅ Correct: Counts distinct unique customer IDsSELECT COUNT(DISTINCT customer_id) AS unique_buyers FROM sales; -- Returns 4You can even combine SUM with DISTINCT:
SELECT SUM(DISTINCT amount) FROM sales; -- Sums unique amounts only7. Filtering Before Aggregating with WHERE 🔍
Remember the SQL execution order! The WHERE clause runs before aggregate functions. This lets you calculate metrics for specific slices of data:
-- Calculate revenue from orders greater than ₹5,000 only:SELECT COUNT(*) AS high_value_order_count, SUM(amount) AS high_value_revenueFROM salesWHERE amount > 5000;Flashcard Checkpoint 🎴
What is the critical behavioral difference between COUNT(*) and COUNT(column_name)?
COUNT(column_name) counts only rows where that specific column is NOT NULL.
How does the AVG() function treat NULL values in a column?