Sort by character length in MySQL

MySQLMySQLi Database

To sort by character length in MySQL use the ORDER BY LENGTH(). Let us first create a table:

mysql> create table orderingAADemo
   -> (
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (1.30 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into orderingAADemo values('A');
Query OK, 1 row affected (0.12 sec)

mysql> insert into orderingAADemo values('B');
Query OK, 1 row affected (0.13 sec)

mysql> insert into orderingAADemo values('AA');
Query OK, 1 row affected (0.20 sec)

mysql> insert into orderingAADemo values('C');
Query OK, 1 row affected (0.12 sec)

mysql> insert into orderingAADemo values('CCC');
Query OK, 1 row affected (0.22 sec)

Following is the query to display records from the table using select command:

mysql> select *from orderingAADemo;

This will produce the following output

+-------+
| Value |
+-------+
| A     |
| B     |
| AA    |
| C     |
| CCC   |
+-------+
5 rows in set (0.00 sec)

Following is the query to sort by character length in descending order:

mysql> select *from orderingAADemo
   -> order by length(Value) DESC, Value;

This will produce the following output

+-------+
| Value |
+-------+
| CCC   |
| AA    |
| A     |
| B     |
| C     |
+-------+
5 rows in set (0.00 sec)
raja
Published on 17-Apr-2019 11:00:27
Advertisements