Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Introduction to SQL for Data Analysis · Lesson 7 of 9

Module Six

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
7
Module 6: SQL Functions and Data Aggregation– Introduction to SQL for Data Analysis. In this module, learners will discover how SQL can count students, calculate average examination scores, add supermarket sales, identify the most expensive products and group information for analysis.

Module 6: SQL Functions and Data Aggregation

Welcome to Module 6 of Introduction to SQL for Data Analysis. In the previous module, you learned how to sort and organise database records using ORDER BY, ASC, DESC and LIMIT.

Now, imagine you are helping a school in Ibadan prepare its end-of-term examination report. The principal wants to know:

  • How many students wrote the examination?
  • What was the average examination score?
  • What was the highest score?
  • What was the lowest score?
  • What was the total score of all students?

Instead of calculating everything manually, you can use SQL functions to perform these calculations quickly.


1. What Are SQL Functions?

SQL functions are built-in instructions that help you perform calculations, process information and analyse data stored in a database.

Think of them as calculators inside SQL. You provide the information, and SQL performs the operation for you.

Examples of SQL functions include:

  • COUNT() – Counts records or values.
  • SUM() – Adds numerical values.
  • AVG() – Calculates the average.
  • MIN() – Finds the smallest value.
  • MAX() – Finds the largest value.

These five functions are known as aggregate functions because they perform calculations on multiple rows and return a result.


2. Understanding the COUNT() Function

The COUNT() function helps you count records or values in a database table.

Imagine a school has a database containing 500 students. The principal wants to know how many students are registered.

You can use:

SELECT COUNT(*)
FROM Students;

SQL counts the number of rows in the Students table.

Counting a Particular Column

You can also count the number of non-NULL values in a particular column.

SELECT COUNT(student_name)
FROM Students;

This counts records where the student_name column contains a value. It does not count NULL values.

Counting Unique Values

What if you want to know how many different states are represented in a school?

Use COUNT(DISTINCT):

SELECT COUNT(DISTINCT state)
FROM Students;

This counts each different state only once.

Real-Life Uses of COUNT()

  • Counting registered students in a school.
  • Counting customers in a supermarket.
  • Counting employees in an organisation.
  • Counting orders received by an online store.
  • Counting products in an inventory database.

3. Understanding the SUM() Function

The SUM() function adds numerical values in a column.

Imagine a supermarket in Ibadan sells different products every day. The manager wants to calculate the total value of all products sold.

Assume you have a table called Sales with these columns:

  • sale_id
  • product_name
  • quantity
  • total_amount

To calculate the total sales amount, write:

SELECT SUM(total_amount)
FROM Sales;

SQL adds all the values in the total_amount column and returns the total.

Another Example

A school wants to calculate the total examination scores of all students.

SELECT SUM(score)
FROM Students;

This adds all numerical values in the score column.

Remember: SUM() works with numerical values. NULL values are ignored, while non-numeric text values are not suitable for this calculation.


4. Understanding the AVG() Function

The AVG() function calculates the average of numerical values.

Average means adding a group of numbers and dividing the total by the number of values included in the calculation.

For example, imagine five students scored:

  • Samuel: 70
  • Mary: 80
  • Peter: 60
  • Esther: 90
  • David: 100

Their total score is 400. Divide 400 by 5 students to get an average of 80.

SQL can calculate this automatically:

SELECT AVG(score)
FROM Students;

SQL calculates the average of the non-NULL values in the score column.

Real-Life Uses of AVG()

  • Calculating the average examination score.
  • Finding the average price of supermarket products.
  • Calculating the average monthly salary of employees.
  • Finding the average amount customers spend.
  • Calculating the average delivery time of orders.

5. Understanding the MIN() Function

The MIN() function finds the smallest value in a column.

Imagine a supermarket manager wants to identify the cheapest product in the store.

Use this query:

SELECT MIN(price)
FROM Products;

SQL returns the lowest numerical value in the price column.

Another Example

Find the lowest examination score in a school.

SELECT MIN(score)
FROM Students;

This helps teachers identify the lowest score recorded.


6. Understanding the MAX() Function

The MAX() function finds the largest value in a column.

For example, a school wants to identify the highest examination score.

SELECT MAX(score)
FROM Students;

SQL returns the highest score recorded in the score column.

Supermarket Example

Find the most expensive product in a supermarket.

SELECT MAX(price)
FROM Products;

The result is the highest numerical price stored in the price column.


7. Combining Multiple Aggregate Functions

You do not need to write a separate query for every calculation. SQL allows you to use several aggregate functions in one query.

Imagine a school wants to see the number of students, total scores, average score, highest score and lowest score.

SELECT
    COUNT(*) AS total_students,
    SUM(score) AS total_score,
    AVG(score) AS average_score,
    MAX(score) AS highest_score,
    MIN(score) AS lowest_score
FROM Students;

This query returns five calculated results from the Students table.

Notice that we used AS to give each result a meaningful name. This is called a column alias.


8. What Is Data Aggregation?

Data aggregation means combining information from multiple records to produce a summary.

Instead of looking at every individual sale, a business may want to know its total sales for the day.

Instead of checking every student's result, a teacher may want to know the average score for the class.

Aggregate functions help you perform these calculations.

Examples of Data Aggregation

  • Total sales made by a supermarket.
  • Average examination scores in a school.
  • Total number of customers registered on a website.
  • Highest salary paid by a company.
  • Lowest product price in an online store.

9. Understanding GROUP BY

The GROUP BY clause helps you organise records into groups based on matching values in a column.

Imagine a school has students in JSS 1, JSS 2 and JSS 3. The principal wants to know how many students are in each class.

You can use GROUP BY to group students according to their classes.

Basic Syntax

SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;

Example 1: Count Students in Each Class

SELECT
    class,
    COUNT(*) AS total_students
FROM Students
GROUP BY class;

SQL groups students with the same class and counts the number of students in each group.

The result may look like this:

class total_students
JSS 120
JSS 225
JSS 318

These figures are examples to help you understand the result.

Example 2: Calculate Average Scores by Class

SELECT
    class,
    AVG(score) AS average_score
FROM Students
GROUP BY class;

This calculates the average examination score for each class.

Example 3: Total Sales by Product Category

SELECT
    category,
    SUM(total_amount) AS total_sales
FROM Sales
GROUP BY category;

This helps a supermarket understand how much money it makes from each product category.


10. Using GROUP BY with Multiple Columns

You can group records using more than one column.

Imagine a school wants to count students according to both class and state.

SELECT
    class,
    state,
    COUNT(*) AS total_students
FROM Students
GROUP BY class, state;

SQL creates groups based on each unique combination of class and state.

This can help the school understand how students from different states are distributed across its classes.


11. Understanding HAVING

The HAVING clause is used to filter grouped results.

Remember that WHERE filters individual records, while HAVING filters groups created using GROUP BY.

Example

Imagine a school wants to display only classes that have more than 20 students.

SELECT
    class,
    COUNT(*) AS total_students
FROM Students
GROUP BY class
HAVING COUNT(*) > 20;

SQL first groups students by class, counts the students in each class, and then displays only groups with more than 20 students.

Another Example: Product Categories

A supermarket wants to find product categories with total sales above ₦100,000.

SELECT
    category,
    SUM(total_amount) AS total_sales
FROM Sales
GROUP BY category
HAVING SUM(total_amount) > 100000;

Only categories whose total sales exceed ₦100,000 will be returned.

WHERE vs HAVING

WHERE HAVING
Filters individual records. Filters grouped results.
Used before GROUP BY. Used after GROUP BY.
Filters values such as age or price. Can filter results using aggregate calculations.

12. Combining WHERE, GROUP BY and HAVING

You can combine filtering, grouping and aggregation in one SQL query.

Imagine a school wants to calculate the average scores of students who scored at least 40, grouped by class. The school only wants to see classes with an average score above 60.

SELECT
    class,
    AVG(score) AS average_score
FROM Students
WHERE score >= 40
GROUP BY class
HAVING AVG(score) > 60;

Here is what happens:

  1. FROM Students selects the Students table.
  2. WHERE score >= 40 filters out scores below 40.
  3. GROUP BY class groups the remaining students by class.
  4. AVG(score) calculates the average score for each class.
  5. HAVING AVG(score) > 60 keeps only classes with averages above 60.

13. Understanding the Order of SQL Clauses

When writing queries that contain filtering, grouping and sorting, it is important to use the correct order.

A common query structure is:

SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition
GROUP BY column_name
HAVING group_condition
ORDER BY column_name DESC
LIMIT number;

The clauses perform different jobs:

  • SELECT – Chooses the information to display.
  • FROM – Identifies the table.
  • WHERE – Filters individual records.
  • GROUP BY – Organises matching records into groups.
  • HAVING – Filters the groups.
  • ORDER BY – Sorts the results.
  • LIMIT – Restricts the number of results.

You do not need to use every clause in every query. Use only the ones required for your task.


14. Practical Business Example

Imagine you are a junior data analyst working for a supermarket in Ibadan. Your manager gives you access to a database containing sales information.

The Sales table contains:

  • sale_id
  • product_name
  • category
  • quantity
  • total_amount
  • sale_date

Your manager asks you to answer these questions:

  1. How many sales records are in the database?
  2. What is the total amount of sales?
  3. What is the average sales amount?
  4. What is the highest sales amount?
  5. What is the lowest sales amount?
  6. How much money was made from each product category?
  7. Which product categories generated more than ₦50,000?
  8. Which product category sold the highest total quantity?

Sample SQL Solutions

-- 1. Count all sales records
SELECT COUNT(*) AS total_sales_records
FROM Sales;

-- 2. Calculate total sales
SELECT SUM(total_amount) AS total_sales
FROM Sales;

-- 3. Calculate average sales amount
SELECT AVG(total_amount) AS average_sales
FROM Sales;

-- 4. Find the highest sales amount
SELECT MAX(total_amount) AS highest_sale
FROM Sales;

-- 5. Find the lowest sales amount
SELECT MIN(total_amount) AS lowest_sale
FROM Sales;

-- 6. Total sales by category
SELECT
    category,
    SUM(total_amount) AS category_sales
FROM Sales
GROUP BY category;

-- 7. Categories with sales above ₦50,000
SELECT
    category,
    SUM(total_amount) AS category_sales
FROM Sales
GROUP BY category
HAVING SUM(total_amount) > 50000;

-- 8. Total quantity sold by category
SELECT
    category,
    SUM(quantity) AS total_quantity
FROM Sales
GROUP BY category
ORDER BY total_quantity DESC;

15. Important Things to Remember

  • Aggregate functions perform calculations on multiple records.
  • COUNT(*) counts rows.
  • COUNT(column_name) counts non-NULL values.
  • SUM() adds numerical values.
  • AVG() calculates an average.
  • MIN() finds the smallest value.
  • MAX() finds the largest value.
  • GROUP BY groups records with matching values.
  • HAVING filters grouped results.
  • WHERE filters individual records before grouping.

16. Knowledge Check

Question 1: Which SQL function counts records?

  1. SUM()
  2. COUNT()
  3. AVG()
  4. MAX()

Question 2: Which function calculates the average of numerical values?

  1. MIN()
  2. COUNT()
  3. AVG()
  4. SUM()

Question 3: Which function adds numerical values?

  1. SUM()
  2. MAX()
  3. MIN()
  4. COUNT()

Question 4: Which function finds the smallest value?

  1. MAX()
  2. MIN()
  3. AVG()
  4. COUNT()

Question 5: Which function finds the largest value?

  1. SUM()
  2. AVG()
  3. MAX()
  4. MIN()

Question 6: Which SQL clause groups records with matching values?

  1. ORDER BY
  2. GROUP BY
  3. LIMIT
  4. WHERE

Question 7: Which clause filters grouped results?

  1. HAVING
  2. SELECT
  3. FROM
  4. LIMIT

Question 8: What is the difference between WHERE and HAVING?

  1. They perform exactly the same task.
  2. WHERE filters individual records, while HAVING filters groups.
  3. HAVING creates databases.
  4. WHERE sorts records.

Question 9: Which query counts the number of students in each class?

  1. SELECT class FROM Students;
  2. SELECT class, COUNT(*) FROM Students GROUP BY class;
  3. DELETE FROM Students;
  4. SELECT COUNT(class) ORDER BY Students;

Question 10: Which SQL function can calculate the total sales amount?

  1. AVG()
  2. COUNT()
  3. SUM()
  4. MIN()

17. Practical Assignment

Create or use a database table called Employees with the following columns:

  • employee_id
  • employee_name
  • department
  • salary
  • city

Write SQL queries to answer these questions:

  1. Count the total number of employees.
  2. Calculate the total salary paid to all employees.
  3. Calculate the average employee salary.
  4. Find the highest employee salary.
  5. Find the lowest employee salary.
  6. Count employees in each department.
  7. Calculate the average salary for each department.
  8. Display departments with more than five employees.
  9. Find departments where the average salary is above ₦150,000.
  10. Arrange departments by their total salary from highest to lowest.

Try solving the questions yourself before checking your answers. You can practise using MySQL, phpMyAdmin or MySQL Workbench.


18. Module Summary

Congratulations! You have completed Module 6. You now understand how SQL can calculate and summarise information stored in a database.

You have learned:

  • How SQL functions work.
  • How to count records using COUNT().
  • How to calculate totals using SUM().
  • How to calculate averages using AVG().
  • How to find the smallest and largest values using MIN() and MAX().
  • How to group records using GROUP BY.
  • How to filter groups using HAVING.
  • How to combine filtering, grouping and sorting in one query.

These skills are important because data analysts use them to turn large amounts of raw information into useful business reports.


Coming Up in Module 7

Combining and Working with Data

In the next module, you will learn how to retrieve information from multiple database tables and combine related records.

You will explore:

  • Understanding relationships between database tables.
  • Introduction to SQL JOINs.
  • INNER JOIN.
  • LEFT JOIN.
  • RIGHT JOIN.
  • FULL OUTER JOIN concepts and MySQL workarounds.
  • UNION and UNION ALL.
  • Introduction to subqueries.

CRMNuggets – Learn. Practice. Get Certified.

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→