HackerRank: [SQL Basic Select] (10/20) Weather Observation Station-5 | Length of string | union & order by in SQL

HackerRank: [Basic Select - 10/20] Weather Observation Station-5 | Length of string | UNION & Order by in SQL

I started studying SQL from a very famous site - HackerRank. Here I will try to provide multiple approaches & solutions to the same problem. It will help you learn and understand SQL in a better way.

Please make use of my blog posts for learning purpose only and feel free to ask your questions in the comment box below in case of any doubt.

Click Here for the previous blog-post in the series.


SQL Problem Statement:

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:

Table: STATION
Table: STATION
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 3 options for the 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.




Sample data in Table (STATION):
ID CITY STATE LAT_N LONG_W
794 Kissee Mills MO 140 73
824 Loma Mar CA 49 131
603 Sandy Hook CT 72 148
478 Tipton IN 34 98
619 Arlington CO 75 93
711 Turner AR 50 101
839 Slidell LA 85 152
.
.
.
754 South Haven MI 145 53
144 Eskridge KS 1




Solution-1: Single Query with UNION (MySQL Query):
(
SELECT CITY, length(CITY) as len
FROM STATION
ORDER BY len, CITY
LIMIT 1
)
UNION
(
SELECT CITY, length(CITY) as len
FROM STATION
ORDER BY len DESC, CITY
LIMIT 1
)

Solution-2: 2 separate queries (MySQL Query):
SELECT CITY, length(CITY) as len FROM STATION ORDER BY len, CITY LIMIT 1;
SELECT CITY, length(CITY) as len FROM STATION ORDER BY len DESC, CITY LIMIT 1;

Sample Output:
Amo 3
Marine On Saint Croix 21




--------------------------------------------------------------------------------
Click here to see solutions for all Machine Learning Coursera Assignments.
&
Click here to see more codes for Raspberry Pi 3 and similar Family.
&
Click here to see more codes for NodeMCU ESP8266 and similar Family.
&
Click here to see more codes for Arduino Mega (ATMega 2560) and similar Family.
Feel free to ask doubts in the comment section. I will try my best to answer it.
If you find this helpful by any mean like, comment and share the post.
This is the simplest way to encourage me to keep doing such work.

Thanks & Regards,
-Akshay P Daga
Post a Comment (0)
Previous Post Next Post