Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 980
Sadi Avatar asked Apr 03 '10 17:04

Sadi


People also ask

How do I sort by size in SQL?

The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.

Is there a length function in MySQL?

MySQL LENGTH() Function The LENGTH() function returns the length of a string (in bytes).

How do I find the length of a column in MySQL?

select char_length(col. column_name) as column_name_length, count(*) as columns, count(distinct tab. table_name) as tables from information_schema. tables as tab inner join information_schema.

How do I find the length of a field 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. However, leading spaces at the start of the string is included when calculating the length.


2 Answers

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; 
like image 111
João Silva Avatar answered Oct 19 '22 23:10

João Silva


For those using MS SQL

SELECT * FROM TEST ORDER BY LEN(field) 
like image 21
mfrederick Avatar answered Oct 20 '22 01:10

mfrederick