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]}")
COUNT counts the number of rows, SUM adds values, AVG calculates average, and MAX finds the highest value.COUNT.Employees?AVG().SELECT AVG(salary) FROM Employees; is the correct syntax. Other options use non-standard functions or expressions.Sales with a column amount having values: 100, 200, 300, 400. What will be the result of the query SELECT MAX(amount) FROM Sales;?amount column has values 100, 200, 300, and 400.MAX(amount) returns the highest value, which is 400.SELECT SUM(price), COUNT FROM Products;COUNT function must be called with parentheses, like COUNT(*) or COUNT(column_name).COUNT without parentheses, which is invalid syntax.Orders with columns order_id, customer_id, and amount. You want to find the average order amount for each customer. Which SQL query correctly uses aggregate functions to achieve this?customer_id and calculate average amount.customer_id and uses AVG(amount), which is correct. SELECT customer_id, SUM(amount) FROM Orders; sums amounts but does not group, so it gives total sum only. SELECT AVG(amount) FROM Orders WHERE customer_id; has invalid WHERE clause usage. SELECT customer_id, COUNT(amount) FROM Orders GROUP BY order_id; groups by order_id, which is wrong for per customer aggregation.Pass the test and this pattern moves unknown