Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the solution for this sql complex interview question?

Tags:

sql

I am pretty good at sql. I have faced this question in interview and was unable to figure out the answer.

Question: There is a location table With 3 columns (source, destination, distance)as show below

Location:

Source - Destination - Distance
Hyderabad - Chennai - 700
Chennai - Hyderabad - 700
Hyderabad - Bangalore -650

As given above , Hyderabad to Chennai or Chennai to Hyderabad both mean the same as the distance will always be same.

So we need to write the query to so that the output should not have such kind of duplicate records.

In the above case output should be

Location:

Source - Destination - Distance
Hyderabad - Chennai - 700
Hyderabad - Bangalore -650
like image 890
singam sanjay Avatar asked Dec 08 '25 08:12

singam sanjay


2 Answers

I think this does what you want under these conditions:

select l.*
from location l
where l.source < l.destination;
like image 186
Gordon Linoff Avatar answered Dec 11 '25 02:12

Gordon Linoff


If your SQL DB/engine supports LEAST/GREATEST (it is an ISO syntax, so many of them do):

select  distinct
        least   (source, destination) as source
       ,greatest(source, destination) as destination
       ,distance

from    location

SQL Fiddle - Postgres
SQL Fiddle - MySQL
SQL Fiddle - Oracle

If not:

select  distinct
        case when source < destination then source else destination end as source
       ,case when source < destination then destination else source end as destination
       ,distance

from    location

SQL Fiddle - SQLite
SQL Fiddle - SQL Server

like image 36
David דודו Markovitz Avatar answered Dec 11 '25 02:12

David דודו Markovitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!