Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL / MySQL - Order By Length of Column

In MySQL, is there a way to order my results by the length (characters) of a column?

For example:

myColumn
________________
lor
lorem
lorem ip
lorem ips
lorem ipsum

I would like to order my results by the smallest column length first, "lor", and ending in the largest column length, "lorem ipsum". This should include column lengths of 0 too.

Any suggestions gratefully received...

like image 227
TheCarver Avatar asked Oct 24 '25 09:10

TheCarver


1 Answers

You can use CHAR_LENGTH() function:

ORDER BY CHAR_LENGTH( column )

Notice that CHAR_LENGTH() works for Unicode strings as well, where LENGTH() is OK for Latin but may give unexpected results with Unicode:

CHAR_LENGTH(str)

Returns the length of the string str, measured in characters. A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

like image 57
ypercubeᵀᴹ Avatar answered Oct 25 '25 23:10

ypercubeᵀᴹ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!