Query: 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.
Sample Input :
Let's say that CITY only has four entries: DEF, ABC, PQRS and WXY
Sample Output:
ABC 3
PQRS 4
If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.
TRY THIS :)
mysql code.... simple one
select CITY,LENGTH(CITY) from STATION order by Length(CITY) asc, CITY limit 1;
select CITY,LENGTH(CITY) from STATION order by Length(CITY) desc, CITY limit 1;
Edit:
The above solution is not working for me as it doesn't sort alphabetically. As commented by @omotto
the following is the proper way to make it work. I have tried in SQL server and it works.
select top 1 city, len(city) from station order by len(city) ASC, city ASC;
select top 1 city, len(city) from station order by len(city) DESC, city ASC;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With