Order by number of chars in MySQL?



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;

Output

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;

Output

This will produce the following output −

+--------+ | Name   | +--------+ | Robert | | David | | John | | Bob | +--------+ 4 rows in set (0.00 sec)
Updated on: 2020-06-30T12:46:58+05:30

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements