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 city,length(city) from (select city,length(city),rank() over(partition by length(city) order by length(city),city asc) as rnk from station)a where a.rnk=1;
select top(1) city, max(len(city)) [Length] from station group by city order by [Length]
select top(1) city, max(len(city)) [Length] from station group by city order by [Length] DESC
Tested in SQL Server 2016
In Oracle:
select * from (select city, min(length(city)) minl from station group by city order by minl, city) where rownum = 1; select * from (select city, max(length(city)) maxl from station group by city order by maxl desc, city) where rownum = 1;
In Oracle it would be,
SELECT CITY,LENGTH(CITY) FROM (SELECT MIN(CITY) CITY FROM STATION WHERE LENGTH(CITY)=(SELECT MIN(LENGTH(CITY)) FROM STATION))
UNION ALL
SELECT CITY,LENGTH(CITY) FROM (SELECT MAX(CITY) CITY FROM STATION WHERE LENGTH(CITY)=(SELECT MAX(LENGTH(CITY)) FROM STATION));
Shortest:
select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity ASC, CITY ASC;
Longest:
select TOP 1 CITY,LEN(CITY) LengthOfCity FROM STATION ORDER BY LengthOfCity DESC, CITY ASC;
This works for HackerRank challenge problem (MS SQL Server).