Skip to content
Back to 50 Concepts
Topic 19 of 50query-executionBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Aggregate Functions Visual Simulator

Step 1 of 3
SQL>SELECT COUNT(*) AS total_orders, COALESCE(SUM(amount), 0) AS total_revenue FROM orders WHERE order_date = CURRENT_DATE;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Aggregate Functions
SQL Input

Initiating Aggregate Functions

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Cash Register: It adds up all money tendered, finds the highest purchase of the day, and reports the daily average.

4. Real-World Example

A monthly financial summary calculating total sales, average ticket size, and total unique buyers.

Monthly Orders
order_idbuyer_idamount
1101150.00
210250.00
3101200.00
Relational walkthrough: SUM(amount) = 400.00, AVG(amount) = 133.33, COUNT(DISTINCT buyer_id) = 2.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Multi-metric summary
SELECT
  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;
Computes entire dataset metrics in a single aggregation step.

6. Important Rules & Behaviors

RuleBehavioral Explanation
NULL ExclusionAll aggregate functions (except COUNT(*)) completely ignore NULL values during computation.
Empty Set BehaviorSUM, AVG, MIN, and MAX on an empty table return NULL; COUNT returns 0.
DISTINCT ModifierCOUNT(DISTINCT col) deduplicates values before calculating the count.
NULL handling in aggregatesSUM, AVG, MIN, and MAX ignore NULL values entirely; COUNT(*) counts all rows including NULLs.
Aggregate restriction in WHEREAggregates 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';
Caution: Never assume SUM() or AVG() return 0 on empty sets; they return NULL.

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

Scenario Question:

What does the query "SELECT COUNT(bonus) FROM staff" return if staff has 10 rows and 4 employees have bonus = NULL?

Select your answer: