
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements