Skip to content
Advertisement

Hackerrank SQL problem to solve in Oracle’s SQL version

Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically. The STATION table is described as follows:

Sample Input

For example, CITY has four entries: DEF, ABC, PQRS and WXY.

Sample Output

ABC  3
PQRS 4

Explanation

When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with lengths and . The longest name is PQRS, but there are options for shortest named city. Choose ABC, because it comes first alphabetically.

Advertisement

Answer

A little bit of analytic functions; sample data in lines #1 – 6; query begins at line #7.

SQL> with station (city) as
  2    (select 'DEF'  from dual union all
  3     select 'ABC'  from dual union all
  4     select 'PQRS' from dual union all
  5     select 'WXY'  from dual
  6    )
  7  select city, len
  8  from (select city,
  9               length(city) len,
 10               rank() over (partition by length(city) order by city) rn
 11         from station
 12        )
 13  where rn = 1
 14  order by city;

CITY        LEN
---- ----------
ABC           3
PQRS          4

SQL>

Reading your comment, it seems you want something like this:

SQL> with station (city) as
  2   (select 'DEF'   from dual union all
  3    select 'ABC'   from dual union all
  4    select 'PQRS'  from dual union all
  5    select 'WXY'   from dual union all
  6    select 'XX'    from dual union all
  7    select 'ABCDE' from dual
  8   )
  9  select city, len
 10  from (select city,
 11               length(city) len,
 12               rank() over (order by length(city)     , city) rna,
 13               rank() over (order by length(city) desc, city) rnd
 14        from station
 15       )
 16  where rna = 1
 17     or rnd = 1
 18  order by len, city;

CITY         LEN
----- ----------
XX             2
ABCDE          5

SQL>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement