Welcome back! In the previous lessons, we’ve covered various types of SQL JOINs, including INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN. You've practiced linking tables to gather desired data, and now it's time to extend that knowledge by joining multiple tables together.
To give you a quick reminder, here are the three tables we are using:
Movies Table
Movie Details Table
Characters Table
The common key linking all these tables is movie_id.
So far, we have focused on joining two tables together. Now we will expand to join multiple tables together.
When joining multiple tables, the process involves using several consecutive JOIN operations to combine data from more than two tables. Here is the generalized syntax for joining multiple tables:
-
SELECT column1, column2, ...: This specifies the columns you want to retrieve from the tables you are joining. You can list columns from any of the tables involved in theJOINs. -
FROM table1: This is the starting table for your query. TheJOINoperations will add information from other tables to this base table. -
JOIN table2: This specifies the second table to join with the first table (table1). -
ON table1.matching_column = table2.matching_column: This condition specifies how to match rows fromtable1andtable2. It uses a common column (here,matching_column) to identify which rows intable1correspond to which rows intable2.
In this code:
- We select
movie_namefrom themoviestable,box_office_million_usdfrom themovie_detailstable, andcharacter_namefrom thecharacterstable. - First, we
INNER JOINthemoviesandmovie_detailstables onmovie_id. - Next, we
INNER JOINthecharacterstable onmovie_id.
The output is:
Let's take a look at joining multiple tables with different types of JOINs.
In this code:
-
FROM movie_details: Start with themovie_detailstable. -
INNER JOIN movies ON movie_details.movie_id = movies.movie_id: Perform anINNER JOINbetweenmovie_detailsandmovieson themovie_idcolumn.- This operation will return only the rows where there are matching
movie_idvalues in bothmovie_detailsandmovies.
- This operation will return only the rows where there are matching
-
RIGHT JOIN characters ON movies.movie_id = characters.movie_id: Perform aRIGHT JOINwith thecharacterstable on themovie_idcolumn from result of the previous .
In this lesson, we put our knowledge of SQL JOINs into practice with multiple examples, covering INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN, and combinations of multiple tables. Each example demonstrates how to retrieve complex data from relational tables efficiently.
Congratulations on completing the lesson and the course! You now have a solid understanding of SQL JOINs and how to use them in PostgreSQL. Continue practicing to reinforce these concepts and explore more complex queries. Great job, and happy querying!
