Q
Problem solve Get help with specific problems with your technologies, process and projects.

# Finding flights without regard to number of stops

We have a Flights table:

```Flights(flight#,from,to)
```
Its data may include:
```('A1','Washington','Paris')
Flight A1 from Washington to Paris

('A2','Toronto','London')
('A2','London','Dubai')
Flight A2 from Toronto to Dubai with
a stop in London

('A3','Toronto','Paris')
('A3','Paris','Dubai')
('A3','Dubai','Tehran')
Flight A3 from Toronto to Tehran
with stops in Paris and Dubai.
```
We may have multiple stops. The question is:
Write a query that gets from (departure) and to (destination) cities and lists all flight numbers that travel from destination to departures without regard to number of stops during flight. For example for from='Toronto' and to='Tehran' give 'A3.' We are also permitted to use DB2 SQL extension if required.

I believe the key to this problem is knowing that the origin of a particular flight will be the only city at which no legs of that flight will arrive. On the same token, the final destination of a flight will be a city from which no legs depart. If these conditions were not the case, it would be in a situation such as one where a flight might loop back to the city of its origin. In this case, more information would be required in order to determine which city was the origin. For this example, we will assume the aforementioned conditions, that is, that flights will not loop back to their origins. Here is our table with its data:

```create table FlightLegs
( FlightID char(2),
FromCity varchar(15),
ToCity varchar(15)
);

insert into FlightLegs values ('A1','Washington','Paris');
insert into FlightLegs values ('A2','Toronto','London');
insert into FlightLegs values ('A2','London','Dubai');
insert into FlightLegs values ('A3','Toronto','Paris');
insert into FlightLegs values ('A3','Paris','Dubai');
insert into FlightLegs values ('A3','Dubai','Tehran');
```
We can easily find the origin cities for the flights by selecting all those legs where the FromCity is not found as a ToCity in another leg. The SQL looks like this:
```select f.FlightID, f.FromCity
from FlightLegs f
where not exists ( select * from FlightLegs
where FlightID = f.FlightID
and ToCity = f.FromCity );
```
This can be extended to find the final destinations for the flights by selecting all those legs where the ToCity is not found as a FromCity in any other legs. By using a self-join to combine these two conditions together, we get our solution:
```select f.FlightID, f.FromCity Origin, t.ToCity FinalDest
from FlightLegs f, FlightLegs t
where f.FlightID = t.FlightID
and not exists ( select * from FlightLegs
where FlightID = f.FlightID
and ToCity = f.FromCity )
and not exists ( select * from FlightLegs
where FlightID = t.FlightID
and FromCity = t.ToCity );
```
Here are the resulting rows from this SQL:
```FLIGHTID ORIGIN          FINALDEST
-------- --------------- ---------------
A1       Washington      Paris
A2       Toronto         Dubai
A3       Toronto         Tehran
```

• The Best SQL Web Links: tips, tutorials, scripts, and more.
• Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
• Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
• Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

#### Start the conversation

Send me notifications when other members comment.

## SearchDataManagement

• ### Databricks Data Ingestion Network brings data to lakehouse

Databricks Ingest entered a public preview in a move by Databricks to enable a lakehouse that combines the best features of the ...

• ### Lessons learned from Credit Karma GraphQL architecture

Credit Karma's vice president of engineering explains why and how the personal finance service is using the GraphQL data query ...

• ### EnterpriseDB looks to grow market for PostgreSQL

Enterprises are increasingly using the open source PostgreSQL database. Read in this Q&A where the growth is coming from and how ...

• ### Tableau 2020.1 highlighted by Viz Animations, Dynamic Parameters

Dynamic Parameters and Viz Animations highlight Tableau's first 2020 platform update and comes nearly four months after ...

• ### Embedded BI software creates common ground for diverse analytics

Learn how embedding separate business intelligence capabilities into one application empowers users to drill down, access and ...

• ### Embedded BI and analytics apps speed workflows, insight access

Embedded BI is fast becoming a focal point for analytics uses as data analysts, developers and business users enjoy faster ...

## SearchSAP

• ### Understand SAP ECC vs. HANA vs. S/4HANA vs. R/3

SAP ECC, HANA, S/4HANA and R/3 are all valuable tools in the IT world, but it's easy to get them confused. Learn about their ...

• ### 5 tips for a successful S/4HANA Cloud implementation

Moving to S/4HANA public cloud can help you save on IT maintenance and simplify real-time analysis. Here's a look at what you can...

• ### Take care of data before SAP S/4HANA migration

In this Q&A, Rajesh Rengarethinam of ERP security vendor Appsian discusses why reviewing data security and business processes are...

## SearchSQLServer

• ### SQL Server database design best practices and tips for DBAs

Good database design is a must to meet processing needs in SQL Server systems. In a webinar, consultant Koen Verbeeck offered ...

• ### SQL Server in Azure database choices and what they offer users

SQL Server databases can be moved to the Azure cloud in several different ways. Here's what you'll get from each of the options ...

• ### Using a LEFT OUTER JOIN vs. RIGHT OUTER JOIN in SQL

In this book excerpt, you'll learn LEFT OUTER JOIN vs. RIGHT OUTER JOIN techniques and find various examples for creating SQL ...

## TheServerSide.com

• ### CSS performance optimization in 5 easy steps

Here are five CSS performance tips to help you avoid website performance problems.

• ### Why the 8 Java primitive data types are not objects

What's the difference between Java primitive types and objects? To start, don't classify primitive types as objects. Let's ...

• ### A brief history of Java: How it forever changed programming

The Java programming language is an important tool in an application developer's quiver. But Java has also undergone many changes...

## SearchDataCenter

• ### Plan for a successful ITIL implementation

Corporate buy-in and training are essential for organizations that decide to adopt the ITIL framework. Admins should also help ...

• ### Learn the main Linux OS components

Linux is one operating choice to run on your infrastructure. Get started with these terms to discover how the OS works and how it...

• ### New Dell EMC PowerEdge servers are built for the rugged edge

New Dell Streaming Media Platform includes two small form factor PowerEdge servers and a Modular Data Center. Dell aims the ...

## SearchContentManagement

• ### Adobe Acrobat DC integrates PDF tools inside Google Drive

With new Google Drive integration, Adobe embeds free features for commenting and annotating PDFs inside Google Docs. Acrobat ...

• ### 4 benefits of business process automation

Companies are automating business processes to improve workflows and use technology effectively. Some benefits of BPA include ...

• ### Test yourself on the differences between SharePoint and OneDrive

Businesses use Microsoft SharePoint and OneDrive capabilities for a number of reasons. Test your knowledge on the differences ...

## SearchHRSoftware

• ### 15 essential employee engagement survey questions

Crafting survey questions that uncover employee engagement issues is challenging. Here are some key questions and a guide to how ...

• ### Trump's H-1B work visa actions disappoint ex-Disney workers

President Donald Trump arrived in office promising to reform the H-1B visa program. But his actions have fallen short of what ...

• ### How real-time analytics can benefit HR

For analytics to be truly useful, it must be embedded into user workflows. Learn how HR tools are incorporating such approaches ...

Close