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

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.
8
Module 7: Combining and Working with Data– Introduction to SQL for Data Analysis. This module introduces database relationships, SQL JOINs, UNION, UNION ALL and subqueries. The explanations use simple school and supermarket examples suitable for beginners.

Module 7: Combining and Working with Data

Welcome to Module 7 of Introduction to SQL for Data Analysis. In the previous module, you learned how to calculate totals, averages, minimum values, maximum values and group records using SQL.

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

Imagine you are working with a school database. The school stores students' information in one table and their examination results in another table. How can you combine both tables to see each student's name and examination score?

SQL provides special commands called JOINs to help you solve this problem.


1. Why Do We Need Multiple Database Tables?

Imagine a school has 1,000 students. Each student has a name, age, class, phone number and examination results.

Storing everything in one huge table can create unnecessary repetition and make information difficult to manage.

Instead, the school can organise information into different tables.

Example: Students Table

student_id student_name class
1SamuelJSS 2
2MaryJSS 1
3PeterJSS 3
4EstherJSS 2

Example: Results Table

result_id student_id subject score
1011Mathematics85
1022Mathematics90
1033Mathematics75
1044Mathematics88

Notice that both tables contain a column called student_id. This column helps SQL identify which examination result belongs to which student.


2. Understanding Primary Keys and Foreign Keys

Before learning JOINs, you need to understand two important database concepts: primary keys and foreign keys.

What Is a Primary Key?

A primary key is a column that uniquely identifies each record in a database table.

For example, in the Students table, every student has a different student_id.

CREATE TABLE Students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    student_name VARCHAR(100),
    class VARCHAR(20)
);

The student_id column is the primary key because each student must have a unique identification number.

What Is a Foreign Key?

A foreign key is a column that refers to a key in another table. It helps establish a relationship between two tables.

In the Results table, student_id connects each examination result to a student in the Students table.

CREATE TABLE Results (
    result_id INT PRIMARY KEY AUTO_INCREMENT,
    student_id INT,
    subject VARCHAR(50),
    score INT,
    FOREIGN KEY (student_id)
    REFERENCES Students(student_id)
);

This relationship helps maintain consistency between the two tables.

Remember:

  • Primary key uniquely identifies a record.
  • Foreign key connects related tables.
  • One table can have relationships with several other tables.

3. What Is an SQL JOIN?

An SQL JOIN is used to combine related information from two or more tables based on a matching column or condition.

Imagine you want to see the names of students alongside their examination scores. The names are stored in the Students table, while the scores are stored in the Results table.

You can use a JOIN to bring the information together.

Basic JOIN Syntax

SELECT column_names
FROM table1
JOIN table2
ON table1.common_column = table2.common_column;

The ON condition tells SQL how the two tables are connected.


4. Understanding INNER JOIN

INNER JOIN returns records that have matching values in both tables.

Imagine a school has a Students table and a Results table. You want to see only students who have examination results.

Use this query:

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
INNER JOIN Results
ON Students.student_id = Results.student_id;

SQL checks the student_id column in both tables and combines records where the values match.

Understanding the Result

student_name subject score
SamuelMathematics85
MaryMathematics90
PeterMathematics75
EstherMathematics88

The result displays information from both tables in one result set.

When Is INNER JOIN Useful?

  • Finding students who have examination results.
  • Finding customers who have placed orders.
  • Finding employees who belong to departments.
  • Finding products that have recorded sales.

5. Understanding LEFT JOIN

A LEFT JOIN returns all records from the left table and matching records from the right table.

If a record in the left table does not have a match in the right table, SQL still displays that record. The columns from the right table will contain NULL values.

Example

Imagine the school wants to see all registered students, including those who have not written an examination.

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
LEFT JOIN Results
ON Students.student_id = Results.student_id;

This query displays every student in the Students table. If a student has no matching result, the result columns will show NULL.

When Is LEFT JOIN Useful?

  • Finding all students, including those without examination results.
  • Finding all customers, including those who have not placed orders.
  • Finding all employees, including those without assigned projects.
  • Finding all products, including those without recorded sales.

Finding Students Without Examination Results

You can combine LEFT JOIN with WHERE to find students who do not have matching records in the Results table.

SELECT
    Students.student_name
FROM Students
LEFT JOIN Results
ON Students.student_id = Results.student_id
WHERE Results.result_id IS NULL;

This is a useful technique for identifying missing related records.


6. Understanding RIGHT JOIN

A RIGHT JOIN returns all records from the right table and matching records from the left table.

If a record in the right table has no match in the left table, SQL still displays it, with NULL values for the columns from the left table.

Example

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
RIGHT JOIN Results
ON Students.student_id = Results.student_id;

This query keeps all records from the Results table and displays matching student information where available.

Remember: LEFT JOIN and RIGHT JOIN depend on the order of the tables in your query.


7. Understanding FULL OUTER JOIN

A FULL OUTER JOIN returns all records from both tables. Matching records are combined, while records without matches are still included with NULL values for the missing side.

Imagine you want to see every student and every examination result, even when a student has no result or a result has no matching student.

A general SQL example is:

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
FULL OUTER JOIN Results
ON Students.student_id = Results.student_id;

Important for MySQL users: MySQL does not directly support FULL OUTER JOIN. You can achieve a similar result by combining LEFT JOIN and RIGHT JOIN using UNION.

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
LEFT JOIN Results
ON Students.student_id = Results.student_id

UNION

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
RIGHT JOIN Results
ON Students.student_id = Results.student_id;

This example combines matching and unmatched records from both tables.


8. Understanding CROSS JOIN

A CROSS JOIN combines every row from the first table with every row from the second table.

Imagine you have three students and two school clubs. A CROSS JOIN creates a combination of every student with every club.

SELECT
    Students.student_name,
    Clubs.club_name
FROM Students
CROSS JOIN Clubs;

If the first table contains 3 records and the second table contains 2 records, the result contains 6 combinations.

CROSS JOIN can be useful when generating combinations, but be careful: large tables can produce very large results.


9. Understanding SQL JOIN Types

JOIN Type What It Returns
INNER JOIN Only matching records from both tables.
LEFT JOIN All records from the left table and matching records from the right.
RIGHT JOIN All records from the right table and matching records from the left.
FULL OUTER JOIN All records from both tables, whether they match or not.
CROSS JOIN Every possible combination of records from both tables.

10. Using Table Aliases in JOIN Queries

Sometimes, database table names are long. Writing them repeatedly can make your SQL queries difficult to read.

SQL allows you to give tables shorter temporary names called aliases.

Example Without Aliases

SELECT
    Students.student_name,
    Results.score
FROM Students
INNER JOIN Results
ON Students.student_id = Results.student_id;

Example With Aliases

SELECT
    s.student_name,
    r.score
FROM Students AS s
INNER JOIN Results AS r
ON s.student_id = r.student_id;

Here, s represents Students and r represents Results.

Aliases make long queries shorter and easier to understand.


11. What Is UNION?

The UNION operator combines the results of two or more SELECT statements into one result.

Imagine a school stores the names of students in two separate tables: CurrentStudents and FormerStudents.

The principal wants to see names from both tables in one list.

SELECT student_name
FROM CurrentStudents

UNION

SELECT student_name
FROM FormerStudents;

SQL combines the results and removes duplicate rows.

Important UNION Rules

  • Each SELECT statement must return the same number of columns.
  • The columns must have compatible data types.
  • The columns must appear in the same order.
  • UNION removes duplicate rows from the combined result.

12. Understanding UNION ALL

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

Example

SELECT student_name
FROM CurrentStudents

UNION ALL

SELECT student_name
FROM FormerStudents;

If the same name appears in both tables, UNION ALL keeps both occurrences.

UNION vs UNION ALL

UNION UNION ALL
Combines query results. Combines query results.
Removes duplicate rows. Keeps duplicate rows.
May require additional work to remove duplicates. Often performs less work because it does not remove duplicates.

13. Introduction to SQL Subqueries

A subquery is a query written inside another SQL query.

It is also called an inner query or nested query.

Imagine you want to find students who scored higher than the average examination score.

First, SQL needs to calculate the average score. Then it can find students whose scores are above that average.

You can achieve this using a subquery:

SELECT
    student_name,
    score
FROM Students
WHERE score > (
    SELECT AVG(score)
    FROM Students
);

The inner query calculates the average score. The outer query displays students whose scores are greater than that average.

Another Example: Products Above Average Price

Imagine a supermarket wants to find products whose prices are higher than the average product price.

SELECT
    product_name,
    price
FROM Products
WHERE price > (
    SELECT AVG(price)
    FROM Products
);

This query helps identify products that are more expensive than the average product price.


14. Using JOINs with WHERE and ORDER BY

You can combine JOINs with filtering and sorting to answer more detailed questions.

Example

A school wants to find students who scored above 70 in Mathematics and arrange their results from highest to lowest.

SELECT
    Students.student_name,
    Results.subject,
    Results.score
FROM Students
INNER JOIN Results
ON Students.student_id = Results.student_id
WHERE Results.subject = 'Mathematics'
AND Results.score > 70
ORDER BY Results.score DESC;

This query combines information from two tables, filters the results and arranges the matching records.


15. Practical Project: School Database

You are helping a school in Ibadan build a simple database report. The school has two tables: Students and Results.

Students Table

  • student_id
  • student_name
  • class
  • state

Results Table

  • result_id
  • student_id
  • subject
  • score

Complete the following tasks:

  1. Display student names alongside their examination scores.
  2. Display all students, including those without examination results.
  3. Display all examination records with matching student names where available.
  4. Find students who do not have examination results.
  5. Find students who scored above 70 in Mathematics.
  6. Find students whose scores are above the average score.
  7. Display students from CurrentStudents and FormerStudents in one list.
  8. Count the number of students in each class.

Sample Solutions

-- 1. Display student names and scores
SELECT
    s.student_name,
    r.subject,
    r.score
FROM Students AS s
INNER JOIN Results AS r
ON s.student_id = r.student_id;

-- 2. Display all students
SELECT
    s.student_name,
    r.subject,
    r.score
FROM Students AS s
LEFT JOIN Results AS r
ON s.student_id = r.student_id;

-- 3. Display all examination records
SELECT
    s.student_name,
    r.subject,
    r.score
FROM Students AS s
RIGHT JOIN Results AS r
ON s.student_id = r.student_id;

-- 4. Find students without examination results
SELECT
    s.student_name
FROM Students AS s
LEFT JOIN Results AS r
ON s.student_id = r.student_id
WHERE r.result_id IS NULL;

-- 5. Students scoring above 70 in Mathematics
SELECT
    s.student_name,
    r.score
FROM Students AS s
INNER JOIN Results AS r
ON s.student_id = r.student_id
WHERE r.subject = 'Mathematics'
AND r.score > 70;

-- 6. Students scoring above the average
SELECT
    student_name,
    score
FROM Students
INNER JOIN Results USING (student_id)
WHERE score > (
    SELECT AVG(score)
    FROM Results
);

-- 7. Combine current and former students
SELECT student_name
FROM CurrentStudents
UNION
SELECT student_name
FROM FormerStudents;

-- 8. Count students in each class
SELECT
    class,
    COUNT(*) AS total_students
FROM Students
GROUP BY class;

These examples assume the tables and columns exist as described. The tables must have compatible data types and matching key values for the JOIN operations to work correctly.


16. Common SQL JOIN Mistakes

Common Mistake Correct Approach
Forgetting the ON condition Specify how the tables are related.
Joining unrelated columns Use matching key columns.
Using ambiguous column names Use table names or aliases before column names.
Expecting LEFT JOIN to return only matching records Remember that it returns every record from the left table.
Using UNION with different column counts Ensure all SELECT statements return the same number of columns.
Confusing UNION and UNION ALL UNION removes duplicates; UNION ALL keeps them.

17. Knowledge Check

Question 1: What is the main purpose of an SQL JOIN?

  1. Delete database records
  2. Combine related information from multiple tables
  3. Create a new database
  4. Sort records alphabetically

Question 2: Which JOIN returns only matching records from both tables?

  1. LEFT JOIN
  2. RIGHT JOIN
  3. INNER JOIN
  4. CROSS JOIN

Question 3: Which JOIN returns all records from the left table?

  1. LEFT JOIN
  2. INNER JOIN
  3. CROSS JOIN
  4. UNION

Question 4: What is a primary key?

  1. A column that uniquely identifies a record
  2. A column containing only names
  3. A database password
  4. A command for sorting records

Question 5: What is a foreign key used for?

  1. Deleting records
  2. Connecting related tables
  3. Changing database passwords
  4. Sorting columns

Question 6: Which SQL operator combines results and removes duplicate rows?

  1. JOIN
  2. UNION
  3. LIMIT
  4. WHERE

Question 7: What is the difference between UNION and UNION ALL?

  1. UNION sorts records and UNION ALL deletes them.
  2. UNION removes duplicate rows, while UNION ALL keeps them.
  3. They always produce different columns.
  4. UNION ALL only works with numbers.

Question 8: What is a subquery?

  1. A query inside another query
  2. A deleted database
  3. A table without columns
  4. A command for creating users

Question 9: Which JOIN returns all possible combinations of records from two tables?

  1. INNER JOIN
  2. LEFT JOIN
  3. CROSS JOIN
  4. RIGHT JOIN

Question 10: Which keyword specifies the matching condition in a JOIN?

  1. GROUP
  2. ON
  3. LIMIT
  4. ORDER

18. Practical Assignment

Create a simple database for a supermarket in Ibadan. The database should contain three tables:

Customers Table

  • customer_id
  • customer_name
  • city

Orders Table

  • order_id
  • customer_id
  • order_date
  • total_amount

OrderItems Table

  • item_id
  • order_id
  • product_name
  • quantity
  • price

Write SQL queries to:

  1. Display all customers and their orders.
  2. Find customers who have not placed any orders.
  3. Find all orders belonging to customers from Ibadan.
  4. Calculate the total amount spent by each customer.
  5. Find customers whose total spending is above ₦50,000.
  6. Display the products purchased in each order.
  7. Find the customer who has spent the most money.
  8. Count the number of orders placed by each customer.

This assignment will help you understand how businesses use related database tables to manage customers, orders and products.


19. Module Summary

Congratulations! You have completed Module 7. You now understand how to combine information from different database tables.

You have learned:

  • Why databases use multiple related tables.
  • What primary keys and foreign keys are.
  • How SQL JOINs work.
  • How to use INNER JOIN.
  • How to use LEFT JOIN and RIGHT JOIN.
  • How FULL OUTER JOIN works and its MySQL workaround.
  • How CROSS JOIN creates combinations.
  • How to combine results using UNION and UNION ALL.
  • How to use subqueries.
  • How to combine JOINs with filtering and sorting.

These skills are important because real-world databases often contain information spread across many related tables.


Coming Up in Module 8

Practical SQL for Data Analysis

In the final module, you will apply the SQL skills you have learned to practical data analysis projects.

You will work on:

  • Creating and exploring a sample database.
  • Retrieving and filtering records.
  • Sorting and organising data.
  • Calculating totals and averages.
  • Combining information from multiple tables.
  • Analysing school and supermarket data.
  • Writing SQL queries to answer real-world questions.
  • Completing a beginner-friendly SQL data analysis project.

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