Query the two cities in STATION with the shortest and longest CITY names - Hacker Rank Solution.

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:


SOLUTION :

SELECT CITY, LENGTH(CITY) AS LEN

FROM (

    SELECT CITY

    FROM STATION

    ORDER BY LENGTH(CITY), CITY

)

WHERE ROWNUM = 1;


SELECT CITY, LENGTH(CITY) AS LEN

FROM (

    SELECT CITY

    FROM STATION

    ORDER BY LENGTH(CITY) DESC, CITY

)

WHERE ROWNUM = 1;



EXPLANATION :
  • We run two separate SELECT queries, one after the other (instead of trying UNION, which sometimes causes issues in SQL*Plus if not used carefully).

  • Each query gets:

    • One city with the shortest name.

    • One city with the longest name.

  • ORDER BY LENGTH(CITY) sorts by name length.

  • ROWNUM = 1 limits the result to just one row.

  • Alphabetical order is used to break ties.

Popular posts from this blog

When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using super keyword - Hacker Rank Solution.

You are given a date. You just need to write the method getDay which returns the day on that date - Hacker Rank Solution.