Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query: order by length of characters?

Tags:

sql

php

mysql

Is it possible to order sql data rows by the total number of characters?

e.g. SELECT * FROM database ORDER BY data.length()

like image 730
TorbenL Avatar asked Aug 31 '10 07:08

TorbenL


People also ask

How do I sort by character length in SQL?

You can use just simply LENGTH(), but beware, because it counts the byte number (which won't give you the expected result with multibyte strings). See Alex Reitborts answer below if you're looking for MS SQL Server variant.

How do I SELECT a specific length in SQL?

Well, you can use the LEN() function to find the length of a String value in SQL Server, for example, LEN(emp_name) will give you the length of values stored in the column emp_name.

How do I find the length of a character 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.

Is there length function in SQL?

You can use SQL length functions in the SELECT statement and other data manipulation statements. Length functions return the length of a column, string, or variable in bytes or characters. For the syntax of these functions, see the Expression segment in the IBM® Informix® Guide to SQL: Syntax .


2 Answers

I think you want to use this: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length

SELECT * FROM table ORDER BY CHAR_LENGTH(field) 

You can use just simply LENGTH(), but beware, because it counts the byte number (which won't give you the expected result with multibyte strings).

like image 57
tamasd Avatar answered Oct 02 '22 22:10

tamasd


SELECT * FROM database ORDER BY Len(data) 
like image 45
Alex Reitbort Avatar answered Oct 02 '22 22:10

Alex Reitbort