TorbenL
TorbenL

Reputation: 1299

SQL Query: order by length of characters?

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

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

Upvotes: 96

Views: 157716

Answers (6)

Sarfraj Ansari
Sarfraj Ansari

Reputation: 1

select from first_name AS name from patients order by len(first_name), first_name

Upvotes: 0

tamasd
tamasd

Reputation: 5913

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

(MySQL/MariaDB specific)

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).

Upvotes: 124

Alex Reitbort
Alex Reitbort

Reputation: 13696

SELECT * FROM table ORDER BY Len(data)

Upvotes: 79

zeeawan
zeeawan

Reputation: 6905

For anyone doing with Sqlite

SELECT * FROM table ORDER BY LENGTH(field) DESC

Upvotes: 8

Kashif
Kashif

Reputation: 14430

SELECT * FROM YourTable ORDER BY LENGTH(Column_Name) DESC

e.g;

SELECT * FROM Customer ORDER BY LENGTH(CustomerName) DESC

Upvotes: 4

Michael Pakhantsov
Michael Pakhantsov

Reputation: 25380

SELECT * FROM table ORDER BY length(data) desc

Where data is varchar field

Upvotes: 12

Related Questions