Search code examples
sqlsqlitesubquerywhere-clause

Exists function


I am trying to answer the following query

write a query that shows flight no (flno), origin and destination for all flights where there exists another flight that goes back from the destination to the origin.

select distinct flno, origin, destination as d from flight 
where exists (select flno, destination from flight where origin = d)

The first two answers are correct but it gives me more answers which does not relate to the question?

Flight Table:

enter image description here


Solution

  • You need to correlate the subquery in the exists condition with the outer query. The logic you appears seems to be:

    select flno, origin, destination
    from flight f
    where exists (
        select 1 
        from flight f1 
        where f1.origin = f.destination and f1.destination = f.origin
    )