Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select shortest and longest string

Tags:

sql

mysql

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

like image 296
Midhun Avatar asked Jun 11 '18 09:06

Midhun


People also ask

How do you select the shortest and longest string in SQL?

SELECT TOP 1 * FROM friends WHERE len(firstName) = (SELECT min(len(firstName)) FROM friends);

How do I find the minimum length of a string in SQL?

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.

How do I find the maximum length of a string in SQL?

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.


2 Answers

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;
like image 73
Midhun Avatar answered Sep 30 '22 17:09

Midhun


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;
like image 42
Jessica G. Avatar answered Sep 30 '22 17:09

Jessica G.