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

Module Eight

๐Ÿ“– 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.
10
Let's complete the course with Module Eight! This final module brings together everything learners have studied, using practical SQL projects based on familiar school and supermarket scenarios. Module 8: Practical SQL Query Projects

MODULE 8: PRACTICAL SQL QUERY PROJECTS

Module Introduction

Congratulations! You have learned many important SQL commands. You now understand how to retrieve, filter, sort, calculate, and manage information stored in a database.

But how do people use these commands in real life?

Imagine you work as a junior database assistant in a school. Your responsibility is to help the school manage student records, examination scores, and class information.

You will need to write SQL queries to answer questions and solve everyday problems.

In this final module, you will complete practical projects that combine the SQL skills you have learned throughout this course.

Learning Objectives

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

  • Create and select a database.
  • Retrieve information using SELECT.
  • Filter records using WHERE.
  • Sort records using ORDER BY.
  • Limit the number of records displayed.
  • Calculate totals, averages, minimums, and maximums.
  • Group information using GROUP BY.
  • Combine query results using UNION.
  • Add, update, and delete records.
  • Build simple SQL solutions for real-life situations.

Lesson 1: Preparing Your SQL Practice Database

Before writing SQL queries, you need a database to work with. For this project, we will create a simple school database.

Step 1: Create the Database

CREATE DATABASE SchoolDB;

This command creates a database called SchoolDB.

Step 2: Select the Database

USE SchoolDB;

The USE command tells MySQL that you want to work with SchoolDB.

Step 3: Create a Students Table

CREATE TABLE Students (
    StudentID INT PRIMARY KEY,
    Name VARCHAR(100),
    Class VARCHAR(20),
    Age INT,
    Score DECIMAL(5,2)
);

Let's understand the columns:

  • StudentID: A unique identification number for each student.
  • Name: Stores the student's name.
  • Class: Stores the student's class.
  • Age: Stores the student's age.
  • Score: Stores the student's examination score.

Lesson 2: Adding Student Records

A newly created table is empty. You need to add records before you can retrieve useful student information.

Use the following SQL statement:

INSERT INTO Students
(StudentID, Name, Class, Age, Score)
VALUES
(1, 'Ade', 'JSS1', 12, 75),
(2, 'Bola', 'JSS1', 13, 90),
(3, 'Chika', 'JSS2', 12, 65),
(4, 'David', 'JSS2', 14, 85),
(5, 'Esther', 'JSS3', 13, 80),
(6, 'Farouk', 'JSS3', 14, 95),
(7, 'Grace', 'JSS1', 12, 88),
(8, 'Michael', 'JSS2', 13, 72);

This command inserts eight student records into the Students table.

Check Your Records

SELECT * FROM Students;

This query displays all the records stored in the Students table.

Lesson 3: Retrieving and Filtering Student Information

A school administrator may want to find particular information about students instead of displaying every record.

Project Task 1: Display All Students

SELECT * FROM Students;

This displays every column and record in the Students table.

Project Task 2: Display Only Student Names

SELECT Name FROM Students;

This displays only the Name column.

Project Task 3: Find Students in JSS1

SELECT * FROM Students
WHERE Class = 'JSS1';

This displays students who belong to JSS1.

Project Task 4: Find Students Who Scored at Least 80

SELECT * FROM Students
WHERE Score >= 80;

This displays students whose scores are 80 or higher.

Project Task 5: Find Students Who Are 13 Years Old

SELECT * FROM Students
WHERE Age = 13;

This displays students whose age is 13.

Lesson 4: Sorting and Limiting Student Records

The school administrator wants to prepare a list of the best-performing students.

Project Task 1: Arrange Students by Score

SELECT * FROM Students
ORDER BY Score DESC;

This arranges students from the highest score to the lowest.

Project Task 2: Display the Top Three Students

SELECT * FROM Students
ORDER BY Score DESC
LIMIT 3;

This displays only the three highest-scoring students.

Project Task 3: Arrange Students Alphabetically

SELECT * FROM Students
ORDER BY Name ASC;

This arranges student names from A to Z.

Project Task 4: Display the Next Three Records

SELECT * FROM Students
ORDER BY StudentID
LIMIT 3 OFFSET 3;

This skips the first three records and displays the next three.

Lesson 5: Performing Calculations with SQL Functions

The school wants to understand how students performed in their examinations. SQL functions can help calculate important statistics.

Project Task 1: Count All Students

SELECT COUNT(*) AS TotalStudents
FROM Students;

Project Task 2: Calculate the Total Scores

SELECT SUM(Score) AS TotalScore
FROM Students;

Project Task 3: Calculate the Average Score

SELECT AVG(Score) AS AverageScore
FROM Students;

Project Task 4: Find the Highest Score

SELECT MAX(Score) AS HighestScore
FROM Students;

Project Task 5: Find the Lowest Score

SELECT MIN(Score) AS LowestScore
FROM Students;

Project Task 6: Calculate Average Scores by Class

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

This query groups students by class and calculates the average score for each class.

Project Task 7: Display Classes with an Average Score of at Least 75

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

This query displays only classes whose average examination score is at least 75.

Lesson 6: Managing Student Records

Database administrators sometimes need to add new records, correct information, or remove records.

Project Task 1: Add a New Student

INSERT INTO Students
(StudentID, Name, Class, Age, Score)
VALUES
(9, 'Daniel', 'JSS1', 13, 82);

Project Task 2: Update a Student's Score

UPDATE Students
SET Score = 90
WHERE StudentID = 9;

This changes Daniel's score to 90.

Project Task 3: Change a Student's Class

UPDATE Students
SET Class = 'JSS2'
WHERE StudentID = 9;

This moves Daniel's record into JSS2.

Project Task 4: Delete a Test Record

DELETE FROM Students
WHERE StudentID = 9;

This removes the record with StudentID 9.

Important: Always check your WHERE condition before running UPDATE or DELETE. Without a WHERE condition, these commands can affect every record in the table.

Lesson 7: Combining Query Results

Imagine that the school stores students in two separate tables. The administrator wants to combine their names into one list.

Example: Create Two Class Tables

CREATE TABLE JSS1_Students (
    StudentID INT,
    Name VARCHAR(100)
);

CREATE TABLE JSS2_Students (
    StudentID INT,
    Name VARCHAR(100)
);

Add Sample Records

INSERT INTO JSS1_Students
VALUES
(1, 'Ade'),
(2, 'Bola');

INSERT INTO JSS2_Students
VALUES
(3, 'Chika'),
(4, 'David');

Combine the Names Using UNION

SELECT Name FROM JSS1_Students
UNION
SELECT Name FROM JSS2_Students;

UNION combines the results and removes duplicate rows.

Combine the Names Using UNION ALL

SELECT Name FROM JSS1_Students
UNION ALL
SELECT Name FROM JSS2_Students;

UNION ALL combines the results while keeping duplicate rows.

Lesson 8: Mini Project - Supermarket Database

You have completed a school database project. Now let's try another practical example.

Imagine you work in a supermarket in Ibadan. The manager wants to keep track of products and their prices.

Step 1: Create a Products Table

CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(100),
    Category VARCHAR(50),
    Price DECIMAL(10,2),
    Quantity INT
);

Step 2: Add Products

INSERT INTO Products
(ProductID, ProductName, Category, Price, Quantity)
VALUES
(1, 'Rice', 'Food', 75000, 10),
(2, 'Beans', 'Food', 45000, 15),
(3, 'Vegetable Oil', 'Food', 12000, 20),
(4, 'Milk', 'Drinks', 8500, 30),
(5, 'Soft Drink', 'Drinks', 1500, 50),
(6, 'Soap', 'Household', 2500, 25),
(7, 'Detergent', 'Household', 5000, 18);

Project Task 1: Display All Products

SELECT * FROM Products;

Project Task 2: Find All Food Products

SELECT * FROM Products
WHERE Category = 'Food';

Project Task 3: Find Products Above โ‚ฆ5,000

SELECT * FROM Products
WHERE Price > 5000;

Project Task 4: Display the Five Most Expensive Products

SELECT * FROM Products
ORDER BY Price DESC
LIMIT 5;

Project Task 5: Calculate the Total Product Quantity

SELECT SUM(Quantity) AS TotalQuantity
FROM Products;

Project Task 6: Find the Average Product Price

SELECT AVG(Price) AS AveragePrice
FROM Products;

Project Task 7: Count Products in Each Category

SELECT
    Category,
    COUNT(*) AS NumberOfProducts
FROM Products
GROUP BY Category;

Project Task 8: Find Products with Low Stock

SELECT * FROM Products
WHERE Quantity < 20;

Project Task 9: Update a Product Price

UPDATE Products
SET Price = 78000
WHERE ProductID = 1;

Project Task 10: Add a New Product

INSERT INTO Products
(ProductID, ProductName, Category, Price, Quantity)
VALUES
(8, 'Bread', 'Food', 2000, 40);

Practical Final Assessment

You are now working as a junior database assistant. Complete the following tasks using the SchoolDB database.

  1. Create a database called SchoolDB.
  2. Create a Students table with StudentID, Name, Class, Age, and Score.
  3. Insert at least ten student records.
  4. Display all students in the database.
  5. Find all students in JSS2.
  6. Display students whose scores are above 70.
  7. Arrange students from the highest score to the lowest.
  8. Display the five students with the highest scores.
  9. Calculate the average examination score.
  10. Find the highest and lowest examination scores.
  11. Count the number of students in each class.
  12. Add a new student to the table.
  13. Update the new student's examination score.
  14. Display unique class names using DISTINCT.
  15. Delete a test record using its StudentID.

Important SQL Commands to Remember

SQL Command What It Does
CREATE DATABASECreates a database.
USESelects a database.
CREATE TABLECreates a table.
INSERT INTOAdds new records.
SELECTRetrieves information.
WHEREFilters records.
ORDER BYSorts query results.
LIMITLimits the number of results.
OFFSETSkips a number of results.
COUNT()Counts records or non-NULL values.
SUM()Calculates a total.
AVG()Calculates an average.
MIN()Finds the smallest value.
MAX()Finds the largest value.
GROUP BYGroups records.
HAVINGFilters grouped results.
DISTINCTReturns unique rows or values.
UNIONCombines query results without duplicate rows.
UPDATEChanges existing records.
DELETERemoves records.
COMMITSaves transaction changes.
ROLLBACKCancels uncommitted transaction changes.

Course Completion

Well done! You have completed the Basic Queries in SQL course.

You have learned how databases work, how to write SQL statements, retrieve information, filter records, sort results, perform calculations, combine query results, and manage database records.

These skills provide a foundation for learning more advanced SQL topics, database management, data analysis, and backend development.

Next Steps

  • Practise writing SQL queries regularly.
  • Build your own school or supermarket database.
  • Learn how to connect SQL databases to applications.
  • Explore advanced SQL topics such as JOINs, subqueries, and database relationships.
  • Continue learning database design and administration.

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