Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Basic Queries in SQL ยท Lesson 8 of 10

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.
8
Module 6: Basic SQL Functions**

MODULE 6: BASIC SQL FUNCTIONS

Module Introduction

Imagine your school has a database containing the examination scores of 500 students. Your teacher wants to know:

  • How many students took the examination?
  • What is the total score of all students?
  • What is the average examination score?
  • What is the highest score?
  • What is the lowest score?

You do not need to calculate everything manually. SQL has special tools called functions that can perform these calculations automatically.

In this module, you will learn how to use COUNT(), SUM(), AVG(), MIN(), MAX(), GROUP BY, and HAVING.

Learning Objectives

By the end of this module, you should be able to:

  • Explain what SQL functions are.
  • Count records using COUNT().
  • Calculate totals using SUM().
  • Calculate averages using AVG().
  • Find the smallest and largest values using MIN() and MAX().
  • Group records using GROUP BY.
  • Filter grouped results using HAVING.
  • Combine SQL functions with SELECT statements.

Lesson 1: Understanding SQL Functions

A function is a built-in instruction that helps a computer perform a particular task.

In SQL, functions help us perform calculations and work with information stored in database tables.

For example:

  • COUNT() counts records or values.
  • SUM() adds numbers together.
  • AVG() calculates the average of numbers.
  • MIN() finds the smallest value.
  • MAX() finds the largest value.

These five functions are known as aggregate functions because they perform calculations across a set of records and return a single result for that set.

Lesson 2: Using COUNT() to Count Records

COUNT() helps you find the number of records or values in a database table.

Imagine a Students table containing the following information:

StudentID Name Score
1Ade75
2Bola90
3Chika65
4David85
5Esther80

To count all the students, use:

SELECT COUNT(*) AS TotalStudents
FROM Students;

Explanation:

  • SELECT tells SQL what information to retrieve.
  • COUNT(*) counts all rows in the table.
  • AS TotalStudents gives the result a readable name.
  • FROM Students identifies the table.

To count students who have a recorded score, use:

SELECT COUNT(Score) AS StudentsWithScores
FROM Students;

COUNT(column) counts only values in that column that are not NULL. NULL means a value is missing or unknown.

Lesson 3: Using SUM() to Calculate Totals

SUM() adds numerical values together.

For example, a school wants to calculate the total examination scores of all students.

SELECT SUM(Score) AS TotalScore
FROM Students;

SQL adds the scores in the Score column and returns the total.

Supermarket Example

Imagine a supermarket has a Products table containing the prices of different products.

ProductID ProductName Price
1Rice75000
2Beans45000
3Vegetable Oil12000
4Milk8500

To calculate the total of the listed product prices, use:

SELECT SUM(Price) AS TotalPrice
FROM Products;

This query adds the numerical values in the Price column. The result is 140500.

Note: This example adds listed prices. It does not calculate actual sales revenue.

Lesson 4: Using AVG() to Calculate Averages

AVG() calculates the average of numerical values.

An average is calculated by adding the numbers together and dividing the total by the number of values.

For example, consider these examination scores:

  • Ade: 75
  • Bola: 90
  • Chika: 65
  • David: 85
  • Esther: 80

To calculate their average score, use:

SELECT AVG(Score) AS AverageScore
FROM Students;

SQL calculates the average of the non-NULL values in the Score column. In this example, the average is 79.

AVG() is useful when calculating average examination scores, average product prices, and average sales values.

Lesson 5: Using MIN() and MAX()

MIN() and MAX() help you find the smallest and largest values in a column.

Understanding MIN()

MIN() returns the smallest non-NULL value in a column.

SELECT MIN(Score) AS LowestScore
FROM Students;

This query finds the lowest examination score in the Students table.

Understanding MAX()

MAX() returns the largest non-NULL value in a column.

SELECT MAX(Score) AS HighestScore
FROM Students;

This query finds the highest examination score in the Students table.

Combining MIN() and MAX()

You can use several functions in one SQL statement.

SELECT
  MIN(Score) AS LowestScore,
  MAX(Score) AS HighestScore,
  AVG(Score) AS AverageScore
FROM Students;

This query returns the lowest score, highest score, and average score in one result.

Lesson 6: Grouping Records with GROUP BY

Sometimes, you may want to calculate information for different groups instead of calculating one result for the entire table.

For example, a school wants to calculate the average examination score for each class.

Consider this Students table:

Name Class Score
AdeJSS170
BolaJSS180
ChikaJSS265
DavidJSS285
EstherJSS390

Use GROUP BY to arrange students into groups based on their classes.

SELECT
  Class,
  AVG(Score) AS AverageScore
FROM Students
GROUP BY Class;

This query:

  1. Identifies the Class column.
  2. Calculates the average score for each class.
  3. Groups students who belong to the same class.
  4. Displays one average result for each class.

GROUP BY is useful when comparing results across departments, classes, product categories, or sales regions.

Lesson 7: Filtering Groups with HAVING

What if the school only wants to display classes with an average score of 75 or higher?

SQL provides the HAVING keyword to filter grouped results.

SELECT
  Class,
  AVG(Score) AS AverageScore
FROM Students
GROUP BY Class
HAVING AVG(Score) >= 75;

This query:

  1. Groups students according to their classes.
  2. Calculates the average score for each class.
  3. Displays only groups whose average score is at least 75.

Understanding WHERE and HAVING

WHERE and HAVING both filter information, but they perform different jobs.

  • WHERE: Filters individual records before grouping.
  • HAVING: Filters groups after GROUP BY.

Example using WHERE:

SELECT *
FROM Students
WHERE Score >= 70;

Example using HAVING:

SELECT Class, AVG(Score) AS AverageScore
FROM Students
GROUP BY Class
HAVING AVG(Score) >= 75;

Remember: WHERE filters rows, while HAVING filters grouped results.

Lesson 8: Combining SQL Functions in Practical Queries

You can combine several SQL functions to answer different questions about your database.

Example 1: Count All Students

SELECT COUNT(*) AS TotalStudents
FROM Students;

Example 2: Find the Total Scores

SELECT SUM(Score) AS TotalScore
FROM Students;

Example 3: Find the Average Score

SELECT AVG(Score) AS AverageScore
FROM Students;

Example 4: Find the Highest and Lowest Scores

SELECT
  MAX(Score) AS HighestScore,
  MIN(Score) AS LowestScore
FROM Students;

Example 5: Count Students in Each Class

SELECT
  Class,
  COUNT(*) AS NumberOfStudents
FROM Students
GROUP BY Class;

Example 6: Calculate Average Product Prices by Category

SELECT
  Category,
  AVG(Price) AS AveragePrice
FROM Products
GROUP BY Category;

Practical Activities

Assume you have a database table called Students with the following columns:

  • StudentID
  • Name
  • Class
  • Age
  • Score

Write SQL queries to complete these tasks:

  1. Count the total number of students.
  2. Calculate the total examination scores.
  3. Calculate the average examination score.
  4. Find the highest examination score.
  5. Find the lowest examination score.
  6. Count the number of students in each class.
  7. Calculate the average score for each class.
  8. Display only classes with an average score greater than 70.

Module Summary

In this module, you have learned how SQL functions help you calculate and understand information stored in a database.

  • COUNT(): Counts records or non-NULL column values.
  • SUM(): Adds numerical values together.
  • AVG(): Calculates the average of numerical values.
  • MIN(): Finds the smallest non-NULL value.
  • MAX(): Finds the largest non-NULL value.
  • GROUP BY: Groups records that share a value.
  • HAVING: Filters grouped results.

Assessment Questions

  1. What is an SQL function?
  2. Which SQL function counts records in a table?
  3. Which function adds numerical values together?
  4. What is the purpose of AVG()?
  5. Which function finds the smallest value?
  6. Which function finds the largest value?
  7. What is the purpose of GROUP BY?
  8. What is the difference between WHERE and HAVING?
  9. What does COUNT(*) count?
  10. Can you use more than one SQL function in a query?

Practical Challenge

A school wants to prepare a simple performance report for its students. Write SQL queries that can:

  1. Count all students in the school.
  2. Find the average score of all students.
  3. Identify the highest and lowest scores.
  4. Calculate the average score for each class.
  5. Display only classes whose average score is at least 75.

What Is Next?

In Module 7, you will learn about combining and managing query results. You will explore how to combine information from different queries and work with database results more effectively.

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.
โ†’