Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Nested Queries
course content

Course Content

Intermediate SQL

Nested QueriesNested Queries

Hi again! In this section, we are going to work with the flight database. It contains the following three tables: passenger, departure, and flights. Let's take a look at them closer and learn their connections.

Let's look at the first table - passenger.

Example

Let's look at the second table - departure.

Example

Let's look at the third table - flights.

Example

Let's see the connection between these three tables.

Example

There is a very common practice of using nested subqueries. Let's take a look at the example, and then discuss the syntax.

Note

To get all columns you have to use the asterisk * with the SELECT statement.

How does this request work? Initially, the nested query will be executed—specifically, the one located within the second part enclosed in parentheses. Subsequently, the primary query, which is initially defined, is filtered based on the result obtained from the nested subquery.

Example

Analysis: Accordingly, numbers of departures that occurred on 2022-07-16 will be found first. (This means that the nested subquery worked). Let's look at the result of the nested request.

Example

Accordingly, the main request will work, displaying all the information of passengers whose departure numbers are 1 and 6. And as a result, if we run the whole query, we will get the following information:

Example

It is time to practice!

Task

You have to create a nested query. To do this, you need to create two queries: a main query and a nested query.

  1. Let's start with the main query: get all the information from the passenger table, where the value of the number_of_departure column must be less or equal to the value that we will receive in the nested query.
  2. For the nested query, you need to extract the number_of_departure column from the departure table, with the following departure time departure_time = '13:15:00'.

Everything was clear?

Section 2. Chapter 1
Switch to desktop for real-world practiceContinue from where you are using one of the options below
some-alt