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
This is an approach with a CTE. First it finds the longest and shortest, than the matching cities:
DECLARE @tbl TABLE(CityName VARCHAR(100));
INSERT INTO @tbl VALUES ('xy'),('Long name'),('very long name'),('middle'),('extremely long name');
WITH MyCTE AS
(
SELECT MAX(LEN(CityName)) AS Longest
,MIN(LEN(CityName)) AS Shortest
FROM @tbl
)
SELECT *
FROM MyCTE
--You must think about the chance of more than one city matching the given length
CROSS APPLY(SELECT TOP 1 CityName FROM @tbl WHERE LEN(CityName)=Longest) AS LongestCity(LongName)
CROSS APPLY(SELECT TOP 1 CityName FROM @tbl WHERE LEN(CityName)=Shortest) AS ShortestCity(ShortName)
The result
Longest Shortest LongName ShortName
19 2 extremely long name xy