# Topic 19: Aggregate Functions
COUNT, SUM, AVG, MIN, MAX, DISTINCT inside aggregates, and understanding how NULLs affect mathematical results.
1. Definition
Aggregate functions compute a single scalar summary value across a collection (or partition) of multiple column values.
2. Explain Like I'm 5
Aggregate functions are like a team captain tallying stats at the end of a game: finding the highest score (MAX), lowest score (MIN), total points (SUM), or average.
3. Animation & Visual Simulation
Interactive Engine TraceAggregate Functions Visual Simulator
SELECT COUNT(*) AS total_orders, COALESCE(SUM(amount), 0) AS total_revenue
FROM orders
WHERE order_date = CURRENT_DATE;Active InputStep 1: Input & Parsing Stage
Initiating Aggregate Functions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
A monthly financial summary calculating total sales, average ticket size, and total unique buyers.
| order_id | buyer_id | amount |
|---|---|---|
| 1 | 101 | 150.00 |
| 2 | 102 | 50.00 |
| 3 | 101 | 200.00 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT COUNT(*) AS total_transactions, COUNT(DISTINCT buyer_id) AS unique_buyers, SUM(amount) AS total_revenue, AVG(amount) AS average_ticket, MIN(amount) AS smallest_sale, MAX(amount) AS largest_sale FROM orders;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| NULL Exclusion | All aggregate functions (except COUNT(*)) completely ignore NULL values during computation. |
| Empty Set Behavior | SUM, AVG, MIN, and MAX on an empty table return NULL; COUNT returns 0. |
| DISTINCT Modifier | COUNT(DISTINCT col) deduplicates values before calculating the count. |
| NULL handling in aggregates | SUM, AVG, MIN, and MAX ignore NULL values entirely; COUNT(*) counts all rows including NULLs. |
| Aggregate restriction in WHERE | Aggregates cannot be used in WHERE clauses because row filtering occurs before aggregation. |
7. Deep Dive: Empty Table Aggregation Behavior
If you run SELECT SUM(salary) FROM employees WHERE 1 = 0, the query returns a single row with NULL (not 0!). If your application expects a number, wrap the aggregate with COALESCE.
-- Returns NULL if no matching rows exist: SELECT SUM(amount) FROM payments WHERE status = 'failed'; -- Returns 0.00 reliably: SELECT COALESCE(SUM(amount), 0.00) FROM payments WHERE status = 'failed';
8. Advantages & Disadvantages
Advantages
- •Enables high-performance data reduction directly in database RAM.
- •Minimizes application network transfer by computing summaries on disk.
Disadvantages & Trade-offs
- •Running aggregates without index-supported filters requires full sequential scans.
9. Common Interview Questions
Q1.What is the critical difference between COUNT(*), COUNT(1), and COUNT(column)?
COUNT(*) and COUNT(1) are semantically identical in modern optimizers: they count the total number of rows in the relation, regardless of whether columns contain NULL. COUNT(column) evaluates the specific column for every row and counts ONLY rows where the column is NOT NULL. If a table has 10 rows and 3 are NULL, COUNT(*) returns 10 while COUNT(col) returns 7.
Q2.Why does AVG(column) produce unexpected results when columns contain NULL?
AVG(col) calculates SUM(col) / COUNT(col), NOT SUM(col) / total_rows. Rows with NULL are omitted from both the numerator and denominator. If 4 employees earn $100 and 1 has NULL salary, AVG() returns 100 / 1 = 100, not 100 / 2 = 50. If you want NULLs treated as zero, you must use AVG(COALESCE(col, 0)).
Q3.What is the performance penalty of COUNT(DISTINCT column) and how do you optimize it?
COUNT(DISTINCT col) requires the engine to collect all values into an in-memory hash set or sort them to deduplicate before counting. In distributed or high-cardinality tables, this is extremely expensive and memory-intensive. For analytics on billions of rows where exact counts are unnecessary, modern databases provide HyperLogLog (HLL) approximation functions (e.g. hyperloglog in PostgreSQL or APPROX_COUNT_DISTINCT in Snowflake).
Q4.What is the FILTER clause in PostgreSQL aggregates?
PostgreSQL supports the standard ANSI FILTER (WHERE condition) clause directly on aggregate functions: SELECT count(*) FILTER (WHERE status = 'active') FROM users; This is cleaner, faster, and more readable than the traditional COUNT(CASE WHEN status = 'active' THEN 1 END) syntax.
Q5.What do aggregate functions return when executed against an empty table?
COUNT(*) returns 0. However, SUM(), AVG(), MIN(), and MAX() all return NULL! If an application expects a number, calling SUM() on an empty result set will return NULL, causing NullPointerExceptions unless wrapped in COALESCE(SUM(val), 0).
10. Interview-Ready Answer
“Aggregate functions condense multiple rows into a single scalar metric. With the exception of COUNT(*), all aggregates omit NULL values, and empty set calculations return NULL for functions like SUM and AVG.”
11. Quick Test
What does the query "SELECT COUNT(bonus) FROM staff" return if staff has 10 rows and 4 employees have bonus = NULL?