You can sort by character length with the help of MySQL's CHAR_LENGTH() function. The function returns the number of characters i.e. 4 of the following string -
AMIT
To sort the string by character length, the syntax is as follows -
select *from yourTableName order by CHAR_LENGTH(yourColumnName);
To understand the above concept, let us first Create a table. Following is the query to create the table -
mysql> create table OrderByCharacterLength −> ( −> BookName varchar(200) −> ); Query OK, 0 rows affected (1.97 sec)
Insert some records in the table with the help of insert command. The query is as follows -
mysql> insert into OrderByCharacterLength values('Let us C'); Query OK, 1 row affected (0.31 sec) mysql> insert into OrderByCharacterLength values('Introduction to C'); Query OK, 1 row affected (0.20 sec) mysql> insert into OrderByCharacterLength values('Data Structure And Algorithm in Java '); Query OK, 1 row affected (0.13 sec) mysql> insert into OrderByCharacterLength values('C in Depth'); Query OK, 1 row affected (0.17 sec) mysql> insert into OrderByCharacterLength values('Java Projects'); Query OK, 1 row affected (0.23 sec)
Let us display all the records in the order of insertion in the above table. The query is as follows -
mysql> select *from OrderByCharacterLength;
The following is the output -
+---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | Introduction to C | | Data Structure And Algorithm in Java | | C in Depth | | Java Projects | +---------------------------------------+ 5 rows in set (0.00 sec)
Here is the query to display all records arranged by character length. If a column value has a minimum length, then it gets higher priority and is displayed first.
The query is as follows -
mysql> select *from OrderByCharacterLength order by CHAR_LENGTH(BookName);
The following is the output -
+---------------------------------------+ | BookName | +---------------------------------------+ | Let us C | | C in Depth | | Java Projects | | Introduction to C | | Data Structure And Algorithm in Java | +---------------------------------------+ 5 rows in set (0.00 sec)
The above is the detailed content of Sorting strings by character length in mYsql?. For more information, please follow other related articles on the PHP Chinese website!