Posts

Showing posts with the label 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 - Hacker Rank Solution.

Image
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 ...