Sort a column ignoring a specific word in MySQL


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name text
   -> );
Query OK, 0 rows affected (1.31 sec)

Insert some records in the table using insert command. Here, we have inserted a name with a specific word “name”, which we need to ignore −

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+-------------+
| Name        |
+-------------+
| John 7      |
| John 6      |
| John 9      |
| name John 3 |
+-------------+
4 rows in set (0.00 sec)

Following is the query to ignore a specific word while sorting a column −

mysql> select *from DemoTable ORDER BY TRIM(REPLACE(LOWER(Name), 'name ', ''));

Output

This will produce the following output −

+-------------+
| Name        |
+-------------+
| name John 3 |
| John 6      |
| John 7      |
| John 9      |
+-------------+
4 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements