SQL Aggregate Functions πΒΆ
Prerequisites: SELECT Statement
Mentor's Note: Aggregates are the "Calculators" of SQL. Instead of looking at one row, they look at a whole column and return a single answer. "What is the total revenue?" or "Who is the oldest student?" π‘
π The Scenario: The School Principal π«ΒΆ
Imagine you are the principal looking at the yearly exam results. - COUNT: "How many students appeared for the exam?" π₯ - SUM: "What is the total of all marks collected?" β - AVG: "What is the class average?" π - MIN / MAX: "What were the lowest and highest scores?" π
π¨ Visual Logic: Many to OneΒΆ
graph TD
A1[Row 1: 50] --> B{Aggregate}
A2[Row 2: 70] --> B
A3[Row 3: 90] --> B
B -- "SUM" --> C[210]
B -- "AVG" --> D[70]
π» 1. The Core FunctionsΒΆ
A. COUNT()ΒΆ
Counts the number of rows.
-- Scenario: Total number of employees
SELECT COUNT(*) FROM employees;
-- Scenario: Count rows where email is NOT NULL
SELECT COUNT(email) FROM employees;
B. SUM()ΒΆ
Calculates the total sum of a numeric column.
C. AVG()ΒΆ
Calculates the average value.
D. MIN() & MAX()ΒΆ
Finds the lowest and highest values.
β οΈ Important: Handling NULLsΒΆ
Most aggregate functions ignore NULL values (except COUNT(*)).
- If you have 3 rows: 10, 20, and NULL.
- AVG will be (10 + 20) / 2 = 15. It ignores the NULL row entirely!
π‘ Pro TipΒΆ
"You can use aggregates with Aliases to make your reports look professional!"
SELECT SUM(salary) AS Total_Payroll FROM employees;