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_length from (select city, char_length(city) city_length
from station order by city, city_length) a
where a.city_length = (select min(a.city_length) from a) or
a.city_length = (select max(a.city_length) from a)
group by a.city_length;
Can anyone help? Thanks
One solution:
select * from (select city, char_length(city) city_length from station order by city, city_length) a group by a.city_length order by a.city_length limit 1;
select * from (select city, char_length(city) city_length from station order by city, city_length) a group by a.city_length order by a.city_length desc limit 1;
For oracle SQL in one resulting table. This will retrieve the min and max city names, and if same length will get the first city sorted in alphabetic order.
Shortest:
Longest:
This works for HackerRank challenge problem (MS SQL Server).
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.
Shortest:
Longest:
I don’t think that we need to use Min and Max functions and Group by is also not required.
We can achieve this using the below code:
but in this case, it will display output in 2 table and if we would like to combine in a single table then we can use Union or Union ALL. Below is the SQL query for the same
here I am nesting the select statement inside a subquery because when we are using order by clause then we cannot use Union or Union ALL directly that is why I have written it inside a subquery.