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
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 to ASC
ending (or DESC
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:
SELECT city
FROM (
SELECT CITY,
ROW_NUMBER() OVER ( ORDER BY LENGTH( CITY ) ASC, CITY ) shortest_rn,
ROW_NUMBER() OVER ( ORDER BY LENGTH( CITY ) DESC, CITY ) longest_rn
FROM station
)
WHERE shortest_rn = 1
OR longest_rn = 1;
If you want to return all the cities with the shortest (or longest) name then use DENSE_RANK
instead of ROW_NUMBER
:
SELECT city
FROM (
SELECT CITY,
DENSE_RANK() OVER ( ORDER BY LENGTH( CITY ) ASC ) shortest_rn,
DENSE_RANK() OVER ( ORDER BY LENGTH( CITY ) DESC ) longest_rn
FROM station
)
WHERE shortest_rn = 1
OR longest_rn = 1
ORDER BY shortest_rn, city; -- Shortest first and order tied lengths alphabetically