Phil Factor's Phrenetic Phoughts

Simple-Talk columnist
The wilder shores of Transact SQL    Phil on Twitter   Phil on SQL Server Central"

Palindromic Transact SQL

Published Wednesday, March 01, 2006 8:45 AM

Palindromes are words or phrases that read the same backwards and forwards. By the same token, Palindromic SQL executes just as well backwards and forwards

A phrase such as ...

  • "Did I do, O God, did I as I said I'd do? Good, I did"
  • "Marge lets Norah see Sharon's telegram"
  • "No, son, onanism's a gross orgasm sin: a no-no, son"
... is a palindrome

You'll notice that punctuation is allowed in palindromes. This means that one can actually construct palindromes fairly simply in Transact SQL, using the PUBS database. For example, the following...

Select zip [srohtua morf] from authors [piz tceles]

will execute happily in either direction just as long as you move the brackets. It is cheating of a sort, though not so brazen as Stephen Fry's

  • "Rettebs, I flahd noces, eh? Ttu, but the second half is better."

    or the dreadful

  • "My girlfriend has a freaking weird name: Eman Driewgnikaerfasahdneirflrigym."

    using the same detestable cheating trick one could come up with...

    Select title, pub_name from (select title, pub_name from titles inner join publishers on titles.pub_ID=publishers.pub_ID) [)DI_bup.srehsilbup=DI_bup.seltit no srehsilbup nioj renni seltit morf eman_bup ,eltit tceles( morf eman_bup ,eltit tceleS]

    As if to legitimise the construction of palindromes, Transact SQL Even has a string function Reverse that makes the whole process easier

    There was, for a short while, a craze for asking interview candidates to write code that checked the validity of a palindrome. It is a silly question, as it is hardly in the van of commercial applications for SQL. I'd prefer to ask questions that are of direct relevance to the rough and tumble of commercial SQL programming. However, I'd be delighted if someone could provide a model answer by writing the shortest palindrome checker in Transact SQL. Remember that some of the most famous palindromes ignore spaces, capitalisation and punctuation. In the meantime, what other tricks can one use for writing palindromic SQL that executes on the PUBS database? String literals? Comments? Executable strings?

  • Comments

     

    Keith Barrows said:

    DROP FUNCTION CheckPalindrome
    GO

    CREATE FUNCTION CheckPalindrome( @palindrome varchar(2000) )
    RETURNS bit
    BEGIN
    DECLARE @a varchar(2000)
    , @ret bit

    SELECT @a = REPLACE(REPLACE(REPLACE(REPLACE(@palindrome, ' ',''), '[',''), ']',''), ',','')
    IF UPPER(@a) = UPPER(REVERSE(@a))
    SET @ret=1
    ELSE
    SET @ret=0

    RETURN @ret
    END
    GO

    SELECT dbo.CheckPalindrome( 'Select zip [srohtua morf] from authors [piz tceles]' )

    SELECT dbo.CheckPalindrome( 'X_Select zip [srohtua morf] from authors [piz tceles]' )

    SELECT dbo.CheckPalindrome( 'Select title, pub_name from (select title, pub_name from titles inner join publishers on titles.pub_ID=publishers.pub_ID) [)DI_bup.srehsilbup=DI_bup.seltit no srehsilbup nioj renni seltit morf eman_bup ,eltit tceles( morf eman_bup ,eltit tceleS]' )

    (The REPLACE line can add on any puctuation to ignore.)
    March 1, 2006 8:00 PM
     

    Michelle Morris said:

    I'm not a developer and I don't play one on TV. Some call me a DBA and others call me unprintable names. Does this qualify as a palindrome checker?

    Michelle

    create table #temp
    (forwards char(38)
    )
    go
    insert into #temp(forwards)
    select 'Marge lets Norah see Sharon''s telegram'
    union
    select 'Is this what you want?'
    go
    select
    case when replace(replace(forwards,'''',''),' ','')
    = reverse(replace(replace(forwards,'''',''),' ',''))
    then left(forwards,5)+'='+'yes, pal'
    else left(forwards,5)+'='+'not a pal'
    end
    from #temp
    March 1, 2006 8:16 PM
     

    Andrew Clarke said:

    /* As the longest palindrome is longer than 8000 characters, one may need to do the function to test the palindrome with a text variable, but as these are horrible, here is a varchar version. Keith's version is good, but this one here actually eliminates all punctuation from the string before doing the comparison. I suspect it is a lot slower, but who cares?

    */
    alter function ufiPalindrome
    (
    @Palindrome varchar(8000)
    )
    RETURNS int AS
    BEGIN
    while PatIndex('%[^a-z0-9]%',@Palindrome)>0
    SELECT @Palindrome=STUFF(@Palindrome, PatIndex('%[^a-z0-9]%',@Palindrome), 1, '')
    RETURN (case when @Palindrome=reverse (@Palindrome) then 1 else 0 end)
    END
    /* regression test
    select dbo.ufiPalindrome ('Select zip [srohtun morf] from authors [piz tceles]')
    select dbo.ufiPalindrome ('Select zip [srohtua morf] from authors [piz tceles]')
    select dbo.ufiPalindrome ('Sit on a potato pan, Otis')
    select dbo.ufiPalindrome ('Reviled did I live, said I, as evil I did deliver.')
    select dbo.ufiPalindrome ('Rise to vote, sir.')
    select dbo.ufiPalindrome ('Won't lovers revolt now? ')
    select dbo.ufiPalindrome ('No "X" in Nixon!')
    select dbo.ufiPalindrome ('Evil rats on no star live')
    select dbo.ufiPalindrome ('Rats drown in WordStar.')
    select dbo.ufiPalindrome ('Pull up if I pull up.')




    March 2, 2006 1:59 PM
     

    NullPointer said:

    I know this comment is way late but I only found this site today.
    After stripping the "punctuation" off the string, couldn't you just say

    return (case when upper(left(palindrome,1)) = upper(right(@palindrome,1) ) then 1 else 0 end

    as if the first and last characters are not the same, the text is not a palindrome?
    August 17, 2006 7:38 AM
     

    Phil Factor said:

    I doubt if that would be sufficient, as it would tell you that it wasn't a palindrome, if the first and last character were different,  but, surely, not that it was if they were the same.  
    August 17, 2006 11:53 AM
    You need to sign in to comment on this blog

















    <March 2006>
    SuMoTuWeThFrSa
    2627281234
    567891011
    12131415161718
    19202122232425
    2627282930311
    2345678
    Virtual Exchange Servers
     Microsoft now supports running Exchange Server 2007 in server virtualization environments, not just on... Read more...

    Virtualizing Exchange: points for discussion
     With the increasing acceptance of the use of Virtualization as a means of providing server... Read more...

    Encouraging .NET Reflector Add-ins
     Jason Haley is well-known for the resources he's provided to developers who wish to extend Reflector's... Read more...

    Using .NET Reflector Add-ins
     .NET Reflector by itself is great, but it really comes into its own with the help of some add-ins. Here... Read more...

    Unique Experiences!
     You'd have thought that a unique constraint was an easy concept - Not a bit of it; it can cause a lot... Read more...