MySQL - How to select data by string length
Asked Answered
S

7

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

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

Shoshone answered 9/12, 2009 at 0:49 Comment(1)
Possible duplicate - https://mcmap.net/q/93793/-mysql-length-vs-char_lengthCochabamba
P
575

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.

Paleoclimatology answered 9/12, 2009 at 0:50 Comment(3)
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.Hadlee
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 2Recruit
@fubo in mySQL 8.0 select LENGTH('Ö'); result is 1. same with CHAR_LENGTH(), OCTET_LENGTH()Eh
S
101
SELECT * FROM table 
ORDER BY LENGTH(column);

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

Shelve answered 9/12, 2009 at 0:51 Comment(0)
S
32

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

Suffragan answered 27/6, 2013 at 8:26 Comment(0)
B
21

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;
Brisbane answered 9/6, 2021 at 6:12 Comment(0)
M
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);
Muleteer answered 1/8, 2016 at 6:18 Comment(0)
M
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.

Mailbox answered 5/9, 2019 at 21:29 Comment(0)
M
-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**
Madeleinemadelena answered 13/1, 2019 at 10:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.