SQL Query: order by length of characters?

Posted on

SQL Query: order by length of characters? – This article will take you through the common SQL errors that you might encounter while working with php, sql,  mysql. The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue. SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem.

SQL Problem :

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

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

Solution :

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

SELECT * FROM database ORDER BY Len(data)

SELECT * FROM table ORDER BY length(data) desc

Where data is varchar field

For anyone doing with Sqlite

SELECT * FROM table ORDER BY LENGTH(field) DESC

SELECT * FROM YourTable ORDER BY LENGTH(Column_Name) DESC

e.g;

SELECT * FROM Customer ORDER BY LENGTH(CustomerName) DESC

Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code.

Leave a Reply

Your email address will not be published. Required fields are marked *