Introduction
When working with data, we often want to find overall information like totals, averages, or counts instead of looking at each item separately. Aggregate functions help us quickly get these summary results from many data points.
Imagine you have a jar of different colored marbles with numbers on them. You want to know how many marbles there are, the total of all numbers, the average number, the biggest number, and the smallest number. Aggregate functions do this kind of summary for data.
┌───────────────┐
│ Data Table │
│ (many rows) │
└──────┬────────┘
│
▼
┌───────────────┐
│ Aggregate │
│ Functions │
│ ┌───────────┐ │
│ │ COUNT │ │
│ │ SUM │ │
│ │ AVG │ │
│ │ MAX │ │
│ │ MIN │ │
│ └───────────┘ │
└──────┬────────┘
│
▼
┌───────────────┐
│ Summary Result│
│ (one value) │
└───────────────┘import sqlite3 conn = sqlite3.connect(':memory:') cur = conn.cursor() cur.execute('CREATE TABLE sales (id INTEGER, amount INTEGER)') cur.executemany('INSERT INTO sales VALUES (?, ?)', [(1, 100), (2, 200), (3, 150), (4, None)]) cur.execute('SELECT COUNT(amount), SUM(amount), AVG(amount), MAX(amount), MIN(amount) FROM sales') result = cur.fetchone() print(f"COUNT: {result[0]}") print(f"SUM: {result[1]}") print(f"AVG: {result[2]}") print(f"MAX: {result[3]}") print(f"MIN: {result[4]}")