Why do we need joins?

Our queries have gotten more complex and expressive with the addition of the where option and its functions. But so far, we’ve only been working with one table at a time. When we need to query across multiple tables at once, we’ll need joins. In this section, we’ll see how to add joins to our queries and learn how to change our select option to make results from multiple columns easier to read.

The term “join” comes from SQL. It’s a language feature that allows us to combine data from two or more tables within the same query. Joins come in many different flavors, depending on how we want to filter the data coming from other tables.

To play with joins, we’ll try a more ambitious query. We’ll look up all the tracks in our database that are longer than 15 minutes and the albums they belong to.

Implementation

This query will touch two different tables—tracks and albums. As mentioned previously, the tracks table has the foreign key album_id, which corresponds to the id column in the albums table. We’ll use those columns as a basis for our join. We’ll use the query bindings we learned about in the last section to help us make sure we’re referring to the right column in the right table.

How to create join?

We’ll use the join keyword to specify the table and the on keyword to specify the column to create the join. The query bindings we learned about in the last chapter clarify which table we’re working within each part of the expression:

Get hands-on with 1400+ tech skills courses.