Bird
Raised Fist0
DBMS Theoryknowledge~6 mins

Aggregate functions (COUNT, SUM, AVG, MAX, MIN) in DBMS Theory - Full Explanation

Choose your learning style10 modes available
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.
Explanation
COUNT
COUNT calculates how many items or rows exist in a dataset or group. It can count all rows or only those with non-empty values in a specific column. This helps understand the size or number of entries in data.
COUNT tells you how many items are in your data or group.
SUM
SUM adds up all the numeric values in a column for the selected rows. It gives the total amount or quantity, useful for things like total sales or total hours worked.
SUM gives the total of all numbers in a group.
AVG
AVG calculates the average value by adding all numbers and dividing by the count of those numbers. It shows the typical or central value in a dataset, like average price or average score.
AVG finds the typical value by averaging numbers.
MAX
MAX finds the largest value in a column among the selected rows. It helps identify the highest number, such as the maximum salary or highest temperature recorded.
MAX shows the biggest number in your data.
MIN
MIN finds the smallest value in a column among the selected rows. It helps identify the lowest number, like the minimum price or lowest score.
MIN shows the smallest number in your data.
Real World Analogy

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.

COUNT → Counting how many marbles are in the jar.
SUM → Adding all the numbers on the marbles together.
AVG → Finding the average number by dividing the total by the number of marbles.
MAX → Picking the marble with the highest number.
MIN → Picking the marble with the lowest number.
Diagram
Diagram
┌───────────────┐
│   Data Table  │
│  (many rows)  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Aggregate     │
│ Functions     │
│ ┌───────────┐ │
│ │ COUNT     │ │
│ │ SUM       │ │
│ │ AVG       │ │
│ │ MAX       │ │
│ │ MIN       │ │
│ └───────────┘ │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Summary Result│
│ (one value)   │
└───────────────┘
This diagram shows how aggregate functions take many rows of data and produce a single summary value.
Key Facts
COUNT → Returns the number of rows or non-null values in a column.
SUM → Calculates the total sum of numeric values in a column.
AVG → Computes the average (mean) of numeric values in a column.
MAX → Finds the highest value in a column.
MIN → Finds the lowest value in a column.
Code Example
DBMS Theory
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]}")
OutputSuccess
Common Confusions
COUNT counts all rows including those with empty or null values.
COUNT counts all rows including those with empty or null values. COUNT(*) counts all rows, but COUNT(column) counts only rows where the column is not null.
SUM and AVG can be used on any data type.
SUM and AVG can be used on any data type. SUM and AVG only work on numeric data types; using them on text or dates causes errors.
MAX and MIN always return the largest or smallest number.
MAX and MIN always return the largest or smallest number. MAX and MIN return the largest or smallest value based on the data type, so for text they compare alphabetically.
Summary
Aggregate functions help summarize many rows of data into single meaningful values like counts, totals, averages, maximums, and minimums.
COUNT counts rows or non-null values, SUM adds numbers, AVG finds the average, MAX finds the largest, and MIN finds the smallest value.
These functions ignore null values except COUNT(*) which counts all rows.

Practice

(1/5)
1. Which aggregate function in SQL is used to find the total number of rows in a table?
easy
A. COUNT
B. SUM
C. AVG
D. MAX

Solution

  1. Step 1: Understand the purpose of each aggregate function

    COUNT counts the number of rows, SUM adds values, AVG calculates average, and MAX finds the highest value.
  2. Step 2: Identify the function that counts rows

    The function that counts rows is COUNT.
  3. Final Answer:

    COUNT -> Option A
  4. Quick Check:

    Counting rows = COUNT [OK]
Hint: COUNT counts rows, SUM adds numbers [OK]
Common Mistakes:
  • Confusing SUM with COUNT
  • Using AVG to count rows
  • Thinking MAX counts rows
2. Which of the following is the correct syntax to find the average salary from a table named Employees?
easy
A. SELECT SUM(salary) / COUNT(*) FROM Employees;
B. SELECT AVG(salary) FROM Employees;
C. SELECT MEAN(salary) FROM Employees;
D. SELECT AVERAGE(salary) FROM Employees;

Solution

  1. Step 1: Recall the standard SQL function for average

    The standard SQL function to calculate average is AVG().
  2. Step 2: Check the syntax correctness

    SELECT AVG(salary) FROM Employees; is the correct syntax. Other options use non-standard functions or expressions.
  3. Final Answer:

    SELECT AVG(salary) FROM Employees; -> Option B
  4. Quick Check:

    Average function = AVG() [OK]
Hint: Use AVG() for average, not AVERAGE or MEAN [OK]
Common Mistakes:
  • Using non-standard function names like AVERAGE or MEAN
  • Trying to calculate average manually with SUM/COUNT
  • Missing parentheses in function call
3. Consider the table Sales with a column amount having values: 100, 200, 300, 400. What will be the result of the query SELECT MAX(amount) FROM Sales;?
medium
A. 400
B. 100
C. 250
D. 1000

Solution

  1. Step 1: Identify the values in the column

    The amount column has values 100, 200, 300, and 400.
  2. Step 2: Apply the MAX function

    MAX(amount) returns the highest value, which is 400.
  3. Final Answer:

    400 -> Option A
  4. Quick Check:

    Maximum of 100,200,300,400 = 400 [OK]
Hint: MAX returns highest value in the column [OK]
Common Mistakes:
  • Choosing SUM or AVG instead of MAX
  • Picking the lowest value by mistake
  • Adding values instead of finding max
4. What is wrong with this SQL query?
SELECT SUM(price), COUNT FROM Products;
medium
A. Products table does not exist
B. SUM cannot be used with price column
C. Missing WHERE clause
D. COUNT requires parentheses with a column or *

Solution

  1. Step 1: Analyze the use of COUNT function

    The COUNT function must be called with parentheses, like COUNT(*) or COUNT(column_name).
  2. Step 2: Identify the syntax error

    The query uses COUNT without parentheses, which is invalid syntax.
  3. Final Answer:

    COUNT requires parentheses with a column or * -> Option D
  4. Quick Check:

    COUNT() needs parentheses [OK]
Hint: Always use COUNT() with parentheses [OK]
Common Mistakes:
  • Writing COUNT without parentheses
  • Assuming SUM can't be used on price
  • Thinking WHERE clause is mandatory
5. You have a table 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?
hard
A. SELECT AVG(amount) FROM Orders WHERE customer_id;
B. SELECT customer_id, SUM(amount) FROM Orders;
C. SELECT customer_id, AVG(amount) FROM Orders GROUP BY customer_id;
D. SELECT customer_id, COUNT(amount) FROM Orders GROUP BY order_id;

Solution

  1. Step 1: Understand the requirement

    We want the average order amount per customer, so we need to group data by customer_id and calculate average amount.
  2. Step 2: Check each query's correctness

    SELECT customer_id, AVG(amount) FROM Orders GROUP BY customer_id; groups by 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.
  3. Final Answer:

    SELECT customer_id, AVG(amount) FROM Orders GROUP BY customer_id; -> Option C
  4. Quick Check:

    Group by customer_id + AVG(amount) [OK]
Hint: Use GROUP BY with AVG for per-group averages [OK]
Common Mistakes:
  • Not using GROUP BY when aggregating per group
  • Using SUM instead of AVG for average
  • Incorrect WHERE clause instead of GROUP BY
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard