How to Order by a specific string in MySQL?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> FirstName varchar(100)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

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

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

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| John      |
| Adam      |
| Sam       |
| Johnny    |
| Joy       |
| Jace      |
+-----------+
6 rows in set (0.00 sec)

Following is the query to order by a specific string. Let’s say you need to first order by substring ‘Jo’ −

mysql> select *from DemoTable
   -> order by case when substring(FirstName, 1, 2) = 'Jo' then 0 else 1 end;

Output

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| John      |
| Johnny    |
| Joy       |
| Adam      |
| Sam       |
| Jace      |
+-----------+
6 rows in set (0.00 sec)

Updated on: 30-Jun-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements