Check If String is a Palindrome using mySQL Reverse function

Mr. Pinal Dave (a MS SQL master) had an interesting post today on his blog.

The question was if it is possible to see if a string is a palindrome or not. This question was asked to him from a friend who wanted to know because he was building captcha and they may display the image mirrored and if the word was a  palindrome, one could not know if it was mirrored or not.

 

When reading his post I thought if this was possible in mySQL and it is.

The mySQL verison is very similar to the T-SQL variant

Note that we use REPLACE to remove all spaces from the @PalinString variable.

[precode]

SET @PalinString = ‘Was it a car or a cat I saw’;
SELECT CASE WHEN
REPLACE(@PalinString, ‘ ‘, ”) = REVERSE(REPLACE(@PalinString, ‘ ‘, ”)) THEN ‘Palindrome’
ELSE ‘Not Palindrome’ END AS Answer

[/precode]

This will retunr the Answer “Palindrome” if @PalinString is or “Not Palindrome” if its not.

I am sure that there are many more situations where this can be applied.

Leave a Reply

Your email address will not be published. Required fields are marked *