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.
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.
| student_id | student_name | class |
|---|---|---|
| 1 | Samuel | JSS 2 |
| 2 | Mary | JSS 1 |
| 3 | Peter | JSS 3 |
| 4 | Esther | JSS 2 |
| result_id | student_id | subject | score |
|---|---|---|---|
| 101 | 1 | Mathematics | 85 |
| 102 | 2 | Mathematics | 90 |
| 103 | 3 | Mathematics | 75 |
| 104 | 4 | Mathematics | 88 |
Notice that both tables contain a column called student_id.
This column helps SQL identify which examination result belongs to which student.
Before learning JOINs, you need to understand two important database concepts: primary keys and foreign keys.
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.
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:
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.
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.
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.
| student_name | subject | score |
|---|---|---|
| Samuel | Mathematics | 85 |
| Mary | Mathematics | 90 |
| Peter | Mathematics | 75 |
| Esther | Mathematics | 88 |
The result displays information from both tables in one result set.
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.
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.
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.
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.
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.
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.
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.
| 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. |
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.
SELECT
Students.student_name,
Results.score
FROM Students
INNER JOIN Results
ON Students.student_id = Results.student_id;
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.
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.
UNION ALL also combines results from multiple SELECT statements.
However, it keeps duplicate rows.
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 | 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. |
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.
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.
You can combine JOINs with filtering and sorting to answer more detailed questions.
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.
You are helping a school in Ibadan build a simple database report. The school has two tables: Students and Results.
Complete the following tasks:
-- 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.
| 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. |
Question 1: What is the main purpose of an SQL JOIN?
Question 2: Which JOIN returns only matching records from both tables?
Question 3: Which JOIN returns all records from the left table?
Question 4: What is a primary key?
Question 5: What is a foreign key used for?
Question 6: Which SQL operator combines results and removes duplicate rows?
Question 7: What is the difference between UNION and UNION ALL?
Question 8: What is a subquery?
Question 9: Which JOIN returns all possible combinations of records from two tables?
Question 10: Which keyword specifies the matching condition in a JOIN?
Create a simple database for a supermarket in Ibadan. The database should contain three tables:
Write SQL queries to:
This assignment will help you understand how businesses use related database tables to manage customers, orders and products.
Congratulations! You have completed Module 7. You now understand how to combine information from different database tables.
You have learned:
These skills are important because real-world databases often contain information spread across many related tables.
In the final module, you will apply the SQL skills you have learned to practical data analysis projects.
You will work on:
CRMNuggets β Learn. Practice. Get Certified.