Welcome to our SQL Joins tutorial! Today, we'll dive into one of the most fundamental and powerful features of SQL: SQL Joins. By the end of this lesson, you'll be able to combine data from multiple tables, enhancing your querying capabilities. Let's get started! 📝
In real-world databases, data is often stored in multiple tables. For example, a library might have separate tables for books, authors, and borrowers. SQL Joins enable us to combine data from these tables based on common columns. This allows us to retrieve a more comprehensive view of our data, helping us answer complex questions.
There are four main types of SQL Joins:
Each of these joins has its purpose, and we'll explore them throughout this tutorial.
An INNER JOIN returns records that have matching values in both tables being joined. Let's look at an example:
Suppose we have two tables: authors and books.
-- authors table
author_id | name
----------|------------------
1 | John Doe
2 | Jane Smith
3 | James Brown
-- books table
book_id | title | author_id
----------|------------------|------------
1 | The Catcher | 1
2 | To Kill a Mockingbird | 1
3 | Pride and Prejudice | 3If we want to retrieve a list of authors along with their books, we can use an INNER JOIN.
SELECT authors.name, books.title
FROM authors
INNER JOIN books
ON authors.author_id = books.author_id;Result:
| name | title |
|------------|------------------|
| John Doe | The Catcher |
| John Doe | To Kill a Mockingbird |
| James Brown| Pride and Prejudice |
As you can see, only the records with matching author_id values from both tables are returned.
Which records are returned by an INNER JOIN?
Stay tuned for more on SQL Joins! In the next section, we'll explore LEFT JOIN.