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
Ascending:
SELECT city, CHAR_LENGTH(city) FROM station ORDER BY CHAR_LENGTH(city), city LIMIT 1;
Descending:
SELECT city, CHAR_LENGTH(city) FROM station ORDER BY CHAR_LENGTH(city) DESC, city LIMIT 1;
In Oracle 12c, this could be done using FETCH..FIRST
Shortest
select * FROM station ORDER BY LENGTH(city) DESC FETCH FIRST 1 ROWS ONLY;
Longest
select * FROM station ORDER BY LENGTH(city) ASC FETCH FIRST 1 ROWS ONLY;
Shortest:
select city, char_length(city) city_length from station order by city_length, city limit 1;
Longest:
select city, char_length(city) city_length from station order by city_length desc, city limit 1;
Initially finding the shortest length of the city
and taking an union with the longest length of the city
. This minimizes the complexity of the query.
(select city, char_length(city) as len_city
from station
order by len_city limit 1)
union ( select city, char_length(city) as len_city
from station
order by len_city desc limit 1)
order by len_city
with cte (rank, city , CityLength)
As
(select dense_rank() over (partition by len(city) order by city asc) as Rank, city, len(city)
from station
where len(city) in
((select max(len(city)) from station)
union (select min(len(city)) from station)))
select city,citylength from cte where rank = 1;
Following query seems simple enough:
select
city, leng
from
(select top 1
city, len(city) leng
from
station
where
len(city) = (select min(len(city)) from station)
order by
city
Union all
select top 1
city, len(city) leng
from
station
where
len(city) = (select max(len(city)) from station)
order by
city) result;
The 1st query inside returns the city with the minimum length, while the 2nd query returns the city with the maximum length.
Hope this helps.