ChatGPT解决这个技术问题 Extra ChatGPT

MySQL: Order by field size/length

Here is a table structure (e.g. test):

Field Name Data Type id BIGINT (20) title varchar(25) Description Text

A query like:

SELECT * FROM TEST ORDER BY description DESC;

But I would like to order by the field size/length of the field description.

The field type will be TEXT or BLOB.


V
Virendra
SELECT * FROM TEST ORDER BY LENGTH(description) DESC;

The LENGTH function gives the length of string in bytes. If you want to count (multi-byte) characters, use the CHAR_LENGTH function instead:

SELECT * FROM TEST ORDER BY CHAR_LENGTH(description) DESC;

Just to add to the answer: if the type is BLOB, you can use OCTET_LENGTH(column_name).
@mastazi according to MySQL documentation: OCTET_LENGTH() is a synonym for LENGTH().
'CHAR_LENGTH' is not a recognized built-in function name. I am facing this error
m
mfrederick

For those using MS SQL

SELECT * FROM TEST ORDER BY LEN(field)

M
Mike Sherov
SELECT * FROM TEST ORDER BY CHAR_LENGTH(description);

'CHAR_LENGTH' is not a recognized built-in function name. I am facing this error