356
SELECT * FROM table ORDER BY string_length(column);

Is there a MySQL function to do this (of course instead of string_length)?

felixmosh
  • 32,615
  • 9
  • 69
  • 88
Gal
  • 23,122
  • 32
  • 97
  • 118

7 Answers7

570

You are looking for CHAR_LENGTH() to get the number of characters in a string.

For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters.

Larzan
  • 9,389
  • 3
  • 42
  • 41
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 152
    Actually, CHAR_LENGTH() should be a better choice. For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters. – András Szepesházi Nov 01 '11 at 14:59
  • It is correct to send an integer parameter to `CHAR_LENGTH`, since if I return the number of characters ? , por ejemplo `CHAR_LENGTH(12)` return `2` – DarkFenix May 06 '17 at 01:28
  • @fubo in mySQL 8.0 ```select LENGTH('Ö');``` result is ```1```. same with ```CHAR_LENGTH()```, ```OCTET_LENGTH()``` – Sathvik Jun 25 '21 at 08:48
98
SELECT * FROM table 
ORDER BY LENGTH(column);

Documentation on the LENGTH() function, as well as all the other string functions, is available here.

Avatar
  • 14,622
  • 9
  • 119
  • 198
Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
32

Having a look at MySQL documentation for the string functions, we can also use CHAR_LENGTH() and CHARACTER_LENGTH() as well.

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
16

In my case I get data using mobile number length greater than 10 digits using the below query

SELECT * FROM table_name WHERE CHAR_LENGTH(mobile) > 10;
Ganesan J
  • 539
  • 7
  • 12
5

The function that I use to find the length of the string is length, used as follows:

SELECT * FROM table ORDER BY length(column);
Flygenring
  • 3,818
  • 1
  • 32
  • 39
Rito
  • 3,092
  • 2
  • 27
  • 40
4

I used this sentences to filter

SELECT table.field1, table.field2 FROM table WHERE length(field) > 10;

you can change 10 for other number that you want to filter.

Jesús Sánchez
  • 705
  • 11
  • 16
-2
select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**
Faisal
  • 4,591
  • 3
  • 40
  • 49