I have a table with one of the columns is of type varchar(city). and want to find the longest and shortest of values stored in that column.
select a.city, a.city
SELECT MAX(LENGTH(transaction_id)) AS Longest ,MIN(LENGTH(transaction_id)) AS Shortest FROM cards
In Oracle, we can do like this
select city, length(city)
from (select city from STATION order by length(city) DESC, city ASC)
where rownum = 1
union
select city, length(city)
from (select city from STATION order by length(city), city ASC)
where rownum = 1;
The idea is to get the longest and shortest city then union them into one result.
Maybe a simpler option since I imagine you are looking for help with a solution to a Hacker Rank question? The addition of limits made it simpler for me to debug where the issue was with the returned error.
SELECT city, length(city) FROM station order by length(city) desc limit 1;
SELECT city, length(city) FROM station order by length(city) asc, city asc limit 1
I think this should work:
SELECT MAX(CITY) , LENGTH(MAX(CITY)) FROM STATION;
SELECT MIN(CITY) , LENGTH(MIN(CITY)) FROM STATION;
This is another way of doing it in MySQL. May not be the best, but still be an option that is logically correct.
select
city,
length(city)
from
station
where
length(city) in
(
select
max(length(city))
from
station
union
select
min(length(city))
from
station
)
order by
length(city) desc,
city asc limit 2;
This Query will work well in your condition these 2 query are exactly same. In the first query we just ordering the recording in descending order to take the city name with the highest length and in the second part we are just taking records in the ascesding order to take city with the minimum lenght all the rest query is same. Kidnly have a look.
Detail:
Ordering all the retrieved records in the descending and ascending order to get the top 1 and take max and min length city.
select Top 1 City,max(len(City)) as Length
from STATION
group by City
ORDER BY Length desc
select Top 1 City,max(len(City)) as Length
from STATION
group by City
ORDER BY Length ASC