How do I select the longest 'string' from a table when grouping

Mysql

Mysql Problem Overview


Example:

SELECT partnumber, manufacturer, condition, SUM(qty), AVG(price), description FROM parts

WHERE [something]

GROUP BY partnumber, manufacturer, condition

I have some descriptions that are blank, and there can be many partnumber, manufacturer, condition values, and on the group it seems to take the first description available, which can be blank. Id like to get the longest description available.

i tried this:

MAX(LENGTH(description)) 

however that returns the number of characters in the string. Is it possible to do what im trying to do in MySQL?

Mysql Solutions


Solution 1 - Mysql

Try ORDER BY LENGTH(description) DESC and use LIMIT 1 to only get the largest.

Solution 2 - Mysql

ORDER BY LENGTH(description) DESC LIMIT 1

This will sort the results from longest to shortest and give the first result (longest.)

Solution 3 - Mysql

SELECT   partnumber, manufacturer, `condition`, SUM(qty), AVG(price), description
FROM     parts
WHERE    [something] AND LENGTH(description) = (
           SELECT MAX(LENGTH(description))
           FROM   parts AS p
           WHERE  p.partnumber   = parts.partnumber
              AND p.manufacturer = parts.manufacturer
              AND p.condition    = parts.condition
         )
GROUP BY partnumber, manufacturer, `condition`

Solution 4 - Mysql

MAX(LENGTH(description)) returns length of longest value in Description column.

Solution 5 - Mysql

If a "description" contains multi-idiom characters, then you should use

MAX(CHAR_LENGTH(description))

For example :

SELECT LENGTH("Это тест, связанный с длиной строки в базе данных")

Resulting in 89.

Whereas :

SELECT CHAR_LENGTH("Это тест, связанный с длиной строки в базе данных")

Resulting in 49.

Solution 6 - Mysql

I found a solution. MAX(description) seems to work just fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1336827View Question on Stackoverflow
Solution 1 - MysqlStilesCrisisView Answer on Stackoverflow
Solution 2 - MysqlScott NelsonView Answer on Stackoverflow
Solution 3 - MysqleggyalView Answer on Stackoverflow
Solution 4 - MysqlTushar KesareView Answer on Stackoverflow
Solution 5 - MysqlRubens AmaralView Answer on Stackoverflow
Solution 6 - Mysqluser1336827View Answer on Stackoverflow