Please see github.com/anusha-murali for all of my repositories.
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:
where LAT_N
is the northern latitude and LONG_W
is the western longitude.
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 3, 3, 4 and 3. The longest name is PQRS, but there are options for shortest named city. Choose ABC, because it comes first alphabetically.
Note: You can write two separate queries to get the desired output. It need not be a single query.
In the following, I’ve used older Oracle (pre-Oracle 12c) syntax as HackerRank doesn’t recognize the newer Oracle syntax. We can use ROWNUM <= 1
to select
the top row from a SELECT statement.
SELECT *
FROM
(SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY) WHERE ROWNUM <= 1;
SELECT *
FROM
(SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC, CITY) WHERE ROWNUM <= 1;
The newer Oracle syntax uses FETCH FIRST n ROWS ONLY
after the ORDER BY
clause. Using the newer Oracle syntax, we can concisely write the above queries as follows:
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY), CITY FETCH FIRST 1 ROWS ONLY;
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY FETCH FIRST 1 ROWS ONLY;