HackerRank: [SQL 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.
Recommended SQL Courses:
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 |
Sample Input:
For example, CITY has four entries: DEF, ABC, PQRS and WXY.
Sample Output:
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):
Sample data in Table (STATION):
Solution-1: Single Query with UNION (MySQL Query):
Solution-2: 2 separate queries (MySQL Query):
Sample Output:
--------------------------------------------------------------------------------
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
No comments