
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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)
- Related Articles
- ORDER BY a specific word in MySQL
- MySQL Order By specific strings?
- Order by on a specific number in MySQL?
- How to order by certain part of a string in MySQL?
- How to ORDER BY last 2 character string in MySQL?
- ORDER BY specific field value first in MySQL
- MySQL Order by a specific column x and display remaining values in ascending order
- How to change a specific char in a MySQL string?
- MySQL order by string with numbers?
- How to arrange data in s specific order in MySQL?
- How to ORDER BY RELEVANCE in MySQL?
- How to ORDER BY LIKE in MySQL?
- How to order by auto_increment in MySQL?
- How to order by timestamp in MySQL?
- How to search a MySQL table for a specific string?

Advertisements