Have you ever wondered if there is a way to check if a string is a palindrome or not in SQL Server? A palindrome is a word, phrase, or sequence that reads the same backward as forward. For example, “A man, a plan, a canal – Panama!” and “Was it a car or a cat I saw?” are palindromes.
Recently, a friend of mine who works in a big MNC approached me with a requirement in their business application. They were building a captcha and needed to ensure that no palindrome words were used as options. He wanted to write a script that would go letter by letter and match them to determine if a word is a palindrome or not.
Initially, I suggested writing a function that compares the word letter by letter. However, there is a simpler way to achieve this using the REVERSE function in SQL Server.
Here’s an example script that checks if a given string is a palindrome:
DECLARE @PalinString VARCHAR(256) = '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]
In this script, we first remove all the spaces from the string using the REPLACE function. Then, we compare the modified string with its reverse using the REVERSE function. If they are the same, we conclude that the string is a palindrome.
It’s important to note that if your string contains punctuation marks or special characters, you may need to remove them as well using the REPLACE function. For example, if your string is “A man, a plan, a canal – Panama!”, you would need to remove the exclamation mark and comma before performing the comparison.
What’s great about this approach is that it works not only with English words but also with words in other languages. SQL Server’s REVERSE function handles characters from different languages correctly.
Now, I would love to hear your thoughts on this function. Do you think there should be a better trick to identify palindromes? If yes, please leave a comment below.