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


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)

Monica Mona
Monica Mona

Student of life, and a lifelong learner

Updated on: 07-Feb-2020

43 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements