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

Module Seven

๐Ÿ“– 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.
9
Module 7: Combining and Managing Query Results**

MODULE 7: COMBINING AND MANAGING QUERY RESULTS

Module Introduction

Imagine you are managing a school database. The school has two tables: one contains students in JSS1, while another contains students in JSS2.

Your teacher wants to see the students from both classes in one list. How can you combine the results?

SQL provides special commands that help you combine results, remove duplicate records, and manage information returned by database queries.

In this module, you will learn about UNION, UNION ALL, DISTINCT, INSERT, UPDATE, DELETE, and transactions.

Learning Objectives

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

  • Explain how SQL combines query results.
  • Use UNION to combine results from two queries.
  • Understand the difference between UNION and UNION ALL.
  • Use DISTINCT to remove duplicate values from query results.
  • Insert new records into a database.
  • Update existing database records.
  • Delete records safely.
  • Understand basic SQL transactions.

Lesson 1: Understanding Combined Query Results

Sometimes, information is stored in different tables. You may want to bring the results together so that they can be viewed as one list.

For example, imagine two tables containing student names.

JSS1 Students

StudentID Name
1Ade
2Bola
3Chika

JSS2 Students

StudentID Name
4David
5Esther
6Farouk

We can combine the names from both tables using the SQL UNION command.

Lesson 2: Combining Results with UNION

UNION combines the results of two or more SELECT statements into one result. It removes duplicate rows from the combined results.

Example

SELECT Name FROM JSS1_Students
UNION
SELECT Name FROM JSS2_Students;

This query displays names from both tables in one result.

For UNION to work correctly, the SELECT statements must return the same number of columns, and the corresponding columns must have compatible data types.

The column names in the final result are generally taken from the first SELECT statement.

Lesson 3: Understanding UNION ALL

UNION ALL also combines results from different SELECT statements. However, unlike UNION, it keeps duplicate rows.

Example

SELECT Name FROM JSS1_Students
UNION ALL
SELECT Name FROM JSS2_Students;

This query combines the names from both tables without removing duplicates.

Difference Between UNION and UNION ALL

UNION UNION ALL
Removes duplicate rows. Keeps duplicate rows.
Returns unique combined rows. Returns all combined rows.
May require extra processing to remove duplicates. Usually avoids duplicate-removal processing.

Lesson 4: Removing Duplicate Results with DISTINCT

Imagine a school database contains the names of students and their classes. Several students belong to the same class.

If you want to see each class only once, you can use DISTINCT.

Example Data

Name Class
AdeJSS1
BolaJSS1
ChikaJSS2
DavidJSS2
EstherJSS3

Use this query:

SELECT DISTINCT Class
FROM Students;

The result contains JSS1, JSS2, and JSS3, with each class appearing once.

DISTINCT is useful when you want to identify unique names, locations, categories, or other values.

Lesson 5: Adding New Records with INSERT

Database information changes regularly. A school may admit a new student, or a supermarket may add a new product.

SQL uses the INSERT INTO statement to add new records to a table.

Example: Adding a New Student

INSERT INTO Students (StudentID, Name, Class, Score)
VALUES (7, 'Grace', 'JSS1', 88);

Explanation:

  • INSERT INTO identifies the table receiving the new record.
  • Students is the table name.
  • The names in brackets are the columns receiving information.
  • VALUES provides the information to insert.

After running this query successfully, Grace's record will be added to the Students table.

Lesson 6: Changing Records with UPDATE

Imagine a teacher discovers that a student's examination score was entered incorrectly. The score needs to be corrected.

SQL uses UPDATE to change information already stored in a database.

Example

UPDATE Students
SET Score = 95
WHERE StudentID = 7;

This query:

  1. Identifies the Students table.
  2. Changes the Score column to 95.
  3. Uses WHERE to identify the student whose ID is 7.

Important safety rule: Always check your WHERE condition before running an UPDATE query. Without WHERE, every record in the table may be updated.

Lesson 7: Removing Records with DELETE

Sometimes, a record needs to be removed from a database. For example, an administrator may need to remove a test record that was entered by mistake.

SQL uses DELETE to remove records from a table.

Example

DELETE FROM Students
WHERE StudentID = 7;

This query removes the student record whose StudentID is 7.

Important safety rule: Always confirm the record you want to remove before running DELETE.

Running DELETE without a WHERE condition can remove every record from the table.

Lesson 8: Understanding SQL Transactions

A transaction is a group of database operations treated as one unit of work. It helps protect data when several related changes must succeed together.

Imagine a bank transfer. Money must be removed from one account and added to another account. Both operations should succeed together.

SQL provides transaction commands such as START TRANSACTION, COMMIT, and ROLLBACK.

START TRANSACTION

Starts a new transaction.

START TRANSACTION;

COMMIT

COMMIT saves the changes made during the transaction.

COMMIT;

ROLLBACK

ROLLBACK cancels changes made in the current transaction that have not been committed.

ROLLBACK;

Simple Transaction Example

START TRANSACTION;

UPDATE Accounts
SET Balance = Balance - 5000
WHERE AccountID = 1;

UPDATE Accounts
SET Balance = Balance + 5000
WHERE AccountID = 2;

COMMIT;

This example transfers 5,000 units of currency from one account to another. Both updates are saved together when COMMIT succeeds.

In a real banking system, additional checks are required, such as confirming sufficient funds and verifying that both account records exist.

Transaction behaviour depends on the database engine. In MySQL, for example, transactional tables such as InnoDB support transactions.

Practical Activities

Assume you have two tables named JSS1_Students and JSS2_Students. Each table contains StudentID and Name columns.

Write SQL queries to complete the following tasks:

  1. Combine the names from both tables using UNION.
  2. Combine the names from both tables using UNION ALL.
  3. Display unique student names from the Students table.
  4. Add a new student named Michael to the Students table.
  5. Change Michael's score to 90.
  6. Delete Michael's record using his StudentID.
  7. Write a transaction that contains two UPDATE statements.

Module Summary

In this module, you learned how to combine query results and manage database records.

  • UNION: Combines query results and removes duplicate rows.
  • UNION ALL: Combines query results and keeps duplicates.
  • DISTINCT: Returns unique values or rows.
  • INSERT INTO: Adds new records to a table.
  • UPDATE: Changes existing records.
  • DELETE: Removes records from a table.
  • START TRANSACTION: Begins a transaction.
  • COMMIT: Saves transaction changes.
  • ROLLBACK: Cancels uncommitted transaction changes.

Assessment Questions

  1. What is the purpose of the UNION command?
  2. What is the difference between UNION and UNION ALL?
  3. Which SQL keyword removes duplicate rows from query results?
  4. Which statement adds a new record to a database table?
  5. What is the purpose of UPDATE?
  6. Which SQL statement removes records from a table?
  7. Why is WHERE important when using UPDATE or DELETE?
  8. What is a database transaction?
  9. What does COMMIT do?
  10. What does ROLLBACK do?

Practical Challenge

You are helping a school administrator manage a student database. Write SQL queries to:

  1. Combine student names from two class tables.
  2. Display unique class names from the Students table.
  3. Add a new student named Daniel to the Students table.
  4. Update Daniel's examination score to 85.
  5. Remove Daniel's record using his StudentID.

Practise these commands in a test database. Do not experiment with UPDATE or DELETE on important records without permission and a backup.

What Is Next?

In Module 8, you will bring together everything you have learned in this course through practical SQL query projects. You will practise retrieving, filtering, sorting, calculating, and managing database information.

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