Course Content
Intermediate SQL
2. Nested Subqueries
4. Left, Right, and Inner Joins
Intermediate SQL
JOIN 2 Tables
It is convenient to combine the related tables, thus forming a temporary table that contains data from both tables. To perform this in SQL, use the JOIN
operator. Let's look at the example.
For example, we have a table of passengers and a table of airplane departures. In the passenger
table, there is only the departure number of the plane, but no more details about the departure. But the departure
table contains all the necessary information about the departure - time and date.
If we combine these two tables we will get the needed information. Let's look.
If you run this query, you will get the following result:
Analysis: In the provided query, we start by extracting the necessary columns from the tables using the SELECT
statement (SELECT name_table.name_column
), where we specify the table's name alongside the column's name. Then, we proceed to join our tables using the JOIN
operator: FROM table1 JOIN table2
. Utilizing the ON
operator, we specify which columns to use for the merge, indicating the respective table names for the columns, i.e., ON table1.column1 = table2.column2
. This approach allows us to merge tables using a shared column present in both tables. In our particular scenario, this shared column is number_of_departure
.
Syntax: To join two tables, you just have to use the JOIN
clause in the following way:
It is time to practice!
Task
You have to join two tables: departure
and flights
. Let's do it step by step.
- Select
departure_date
, anddeparture_time
fromdeparture
table; - Select
start_point_flight
,end_point_flight
,travel_time
fromflights
table; - Join these two tables using the
JOIN
statement by theflight_number
column.
Everything was clear?