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;
You query requires just a few tweaks. The fundamental problem is that you cannot use
a
in the subquery as you are doing:That said, a simpler way to write the query is:
For oracle :
Ascending:
Descending:
Tested in SQL Server 2016
In Oracle (and any other language that supports analytic functions), using the
ROW_NUMBER
analytic function you can assign the rows a unique number according toASC
ending (orDESC
ending) length of the city. Since there may be multiple rows with the same length then a secondary order can be applied to get the first city of that length alphabetically. Then all you need is an outer query to filter the results to only the shortest (or longest) name:If you want to return all the cities with the shortest (or longest) name then use
DENSE_RANK
instead ofROW_NUMBER
:For shortest name of city :
For longest name of city :