Is it possible to select the shortest and longest strings by characters in a table?
I have a CITY
column of type VARCHAR(20)
and I want to select the shortest and longest city names in alphabetical order by length.
I did like this
SELECT CITY,LENGTH(CITY) FROM STATION WHERE LENGTH(CITY) IN ( SELECT MAX(LENGTH(CITY)) FROM STATION UNION SELECT MIN(LENGTH(CITY)) FROM STATION ) ORDER BY CITY ASC;
When ordered alphabetically, Let the CITY names be listed as ABC, DEF, PQRS, and WXY, with the respective lengths 3,3,4, and 3. The longest-named city is obviously PQRS, but there are options for the shortest-named city; I have to select ABC because it comes first alphabetically.
My query ended up with all three CITY having length 3.
ABC 3 DEF 3 PQRS 4 WXY 3
The result of SELECT must be
ABC 3 PQRS 4
SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends);
SQL Server databases use LEN or DATALENGTH to find field width. It also has its own function to find the maximum length of a column – COL_LENGTH. SELECT MIN(LENGTH(<column_name>)) AS MinColumnLength FROM Table; If we include any non-aggregate functions into our query then we need a GROUP BY clause.
SQL Server LEN() Function The LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length.
Anyway i got the answer
SELECT CITY,LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) IN (
SELECT MAX(LENGTH(CITY))
FROM STATION
UNION
SELECT MIN(LENGTH(CITY))
FROM STATION
)
ORDER BY LENGTH(CITY) DESC,CITY ASC LIMIT 2;
I know you have chosen your answer already, but here is a shorter answer that might help. This is using Microsoft MySQL Server but it can also be easily translated to any other type using the call LIMIT instead of TOP.
Shortest Length
SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) ASC, CITY ASC;
Longest Length
SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) DESC, CITY ASC;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With