Skip to main content
Practice

1

deck

1. What Are Joins?

In a relational database, data is often stored in multiple related tables. A join allows you to combine rows from two or more tables based on a related column.

It helps unify scattered data into a single query result.


2. Why Use Joins?

Joins are useful when you need to:

  • Answer questions that span multiple tables
  • Link related rows, such as orders and customers
  • Prevent duplicate data from being stored in a single table

They are essential for effective relational database design and querying.


===

3. Example: Students and Classes

You have two tables:

students

student_idname
1Alex
2Sara

enrollments

student_idclass_name
1Math
1Science
2History

To list each student and their class, you can use a join on student_id.


===

4. How Joins Work

You combine rows where values in a related column match:

SELECT students.name, enrollments.class_name
FROM students
JOIN enrollments ON students.student_id = enrollments.student_id;

This outputs all student-class pairs based on matching student_id.


===

5. Common Join Types

Join TypeDescription
INNER JOINRows with matches in both tables
LEFT JOINAll rows from the left + matches
RIGHT JOINAll rows from the right + matches
FULL OUTER JOINAll rows from both tables (matches optional)

Each type determines which unmatched rows (if any) are included.

SELECT ...
FROM tableA
LEFT JOIN tableB ON tableA.id = tableB.id;

In this example, the left table is tableA and the right table is tableB.

The LEFT JOIN will return all rows from tableA and the matching rows from tableB.

If there is no match, the result will contain NULL values for the columns from tableB.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.