Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query the two cities in STATION with the shortest and longest CITY names, [closed]

Tags:

sql

oracle

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
like image 317
krishna beenavoina Avatar asked Aug 24 '16 17:08

krishna beenavoina


People also ask

How do you select the one that comes first when ordered alphabetically in SQL?

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.


1 Answers

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;
like image 94
user7330784 Avatar answered Nov 15 '22 18:11

user7330784