Tutorialspoint

1 Answer
karthikeya Boyini

To order by number of chars, use ORDER BY and LENGTH() method. Following is the syntax −

select *from yourTableName
order by LENGTH(yourColumnName) DESC;

Let us first create a table −

mysql− create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

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

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

mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.26 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Name   |
+--------+
| John   |
| Robert |
| Bob    |
| David  |
+--------+
4 rows in set (0.00 sec)

Following is the query to order by number of chars −

mysql> select *from DemoTable
   -> order by LENGTH(Name) DESC;

This will produce the following output −

+--------+
| Name   |
+--------+
| Robert |
| David  |
| John   |
| Bob    |
+--------+
4 rows in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.