# How can we reverse a MySQL string connected by the dash?

MySQLMySQLi Database

MySQL has function name REVERSE() with the help of which we can reverse the string. But suppose if we want to reverse the string connected by dash then by using REVERSE() function will not give appropriate result as shown in the following example:

mysql> Select REVERSE('AB-CD-EF');
+---------------------+
| REVERSE('AB-CD-EF') |
+---------------------+
| FE-DC-BA            |
+---------------------+
1 row in set (0.00 sec)

The appropriate result would be ‘EF-CD-AB’ and for getting such output we can use SUBSTRING_INDEX() function along with Instr() function. It is demonstrated as follows:

mysql> Select CONCAT(SUBSTRING_INDEX('AB-CD-EF','-',-1), '-', substr('AB-CD-EF',instr('AB-CD-EF',"-")+1, instr('AB-CD-EF',"-")),LEFT('AB-CD-EF',LOCATE('-','AB-CD-EF') -1))As 'Reversed';
+-----------+
| Reversed  |
+-----------+
| EF-CD-AB  |
+-----------+
1 row in set (0.00 sec)


Published on 20-Feb-2018 11:38:05