Order strings by length of characters IN mYsql?


You can order by length of characters with the help of CHAR_LENGTH() function from MySQL. The function returns the number of characters i.e. 4 for the following string −

AMIT

To order strings by length of characters, the following is the syntax −

select *from yourTableName order by CHAR_LENGTH(yourColumnName);

To understand the above concept, let us first create a table. The following is the query to create a 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 records in a sequence as inserted in the table above. 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 that display all records arranged according to the length of characters. If a column value has minimum length then it gets higher priority and will get 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)

Updated on: 30-Jul-2019

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements