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:
Instead of calculating everything manually, you can use SQL functions to perform these calculations quickly.
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.
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.
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.
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.
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:
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.
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.
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:
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.
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.
Find the lowest examination score in a school.
SELECT MIN(score)
FROM Students;
This helps teachers identify the lowest score recorded.
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.
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.
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.
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.
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.
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
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 1 | 20 |
| JSS 2 | 25 |
| JSS 3 | 18 |
These figures are examples to help you understand the result.
SELECT
class,
AVG(score) AS average_score
FROM Students
GROUP BY class;
This calculates the average examination score for each class.
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.
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.
The HAVING clause is used to filter grouped results.
Remember that WHERE filters individual records, while
HAVING filters groups created using GROUP BY.
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.
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 | 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. |
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:
FROM Students selects the Students table.WHERE score >= 40 filters out scores below 40.GROUP BY class groups the remaining students by class.AVG(score) calculates the average score for each class.HAVING AVG(score) > 60 keeps only classes with averages above 60.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.
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:
Your manager asks you to answer these questions:
-- 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;
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.Question 1: Which SQL function counts records?
Question 2: Which function calculates the average of numerical values?
Question 3: Which function adds numerical values?
Question 4: Which function finds the smallest value?
Question 5: Which function finds the largest value?
Question 6: Which SQL clause groups records with matching values?
Question 7: Which clause filters grouped results?
Question 8: What is the difference between WHERE and HAVING?
Question 9: Which query counts the number of students in each class?
Question 10: Which SQL function can calculate the total sales amount?
Create or use a database table called Employees with the following columns:
Write SQL queries to answer these questions:
Try solving the questions yourself before checking your answers. You can practise using MySQL, phpMyAdmin or MySQL Workbench.
Congratulations! You have completed Module 6. You now understand how SQL can calculate and summarise information stored in a database.
You have learned:
These skills are important because data analysts use them to turn large amounts of raw information into useful business reports.
In the next module, you will learn how to retrieve information from multiple database tables and combine related records.
You will explore:
CRMNuggets – Learn. Practice. Get Certified.