Order By Length of Column in MySQL

MySQLMySQLi Database

To order by length of column in MySQL, use ORDER BY LENGTH.

Let us first create a table −

mysql> create table DemoTable715 (UserMessage varchar(100));
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable715 values('Aw');
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable715 values('Awe');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable715 values('A');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable715 values('Awes');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable715 values('Awesom');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable715 values('Awesome');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable715;

This will produce the following output -

+-------------+
| UserMessage |
+-------------+
| Aw          |
| Awe         |
| A           |
| Awes        |
| Awesom      |
| Awesome     |
+-------------+
6 rows in set (0.00 sec)

Following is the query to order by length of column −

mysql> select *from DemoTable715 order by length(UserMessage);

This will produce the following output -

+-------------+
| UserMessage |
+-------------+
| A           |
| Aw          |
| Awe         |
| Awes        |
| Awesom      |
| Awesome     |
+-------------+
6 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 10:42:25
Advertisements