Search This Blog

String is Palindrome or Not in SQL

String is Palindrome or Not in SQL

In order to test your logic many interviewer have asked this question write a query that will return where the input string is Palindrome or Not.
Most of developers are aware of palindrome words and Sentences just to recall it here is a brief defination of  palindrome:

palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction...From Wiki

Eg-Words-Civic,Mom,DaD,Madam,Level

Sentences-1-Sir, I demand, I am a maid named Iris
                 2- Never odd or even

So below is the sql query that will tell wheather a string or a word is palindrome or not

DECLARE @String NVARCHAR(100) = 'Never odd or even'
SELECT CASE WHEN REPLACE(@String, ' ', '') = REVERSE(REPLACE(@String, ' ', ''))
THEN 'Palindrome'
ELSE 'String is not Palindrome' END [Output]
GO

Output
Palindrome

DECLARE @String NVARCHAR(100) = 'Never odd '
SELECT CASE WHEN REPLACE(@String, ' ', '') = REVERSE(REPLACE(@String, ' ', ''))
THEN 'Palindrome'
ELSE 'String is not Palindrome' END [Output]
GO

Output
String is not Palindrome

Explanation-We have used two function in the query one is Replace which is replacing space with no space between the words second one is Reverse which is reversing the string after removing space in the string if string matches then Palindrome else not Palindrome
below is simple example of Reverse and Remove Function.

SELECT REPLACE('abc','b','c')--acc

SELECT REVERSE ('abc')--cba

1 comment:

  1. Thanks for your comment. Please drop me an email on Rakesh.29nov@gmail.com. I will share the details with you.

    ReplyDelete