Find out anagram using SQL

Any word or phrase that exactly reproduces the letters in another order is an anagram. For example: “Hamlet” is an anagram of the word “Amleth”. We will show u a query today which can determine if two given words are anagram or not. We have used a Tally table for parsing the given strings. It has only one column called ‘N’ and the values of this column are like 1,2,3,4…….100

DROP TABLE #a
DROP TABLE #b

DECLARE @str1 VARCHAR(30)
DECLARE @str2 VARCHAR(30)

SET @str1 = ‘ramy’
SET @str2 = ‘mary’

SELECT N, SUBSTRING(@str1,N,1)letters
INTO #a
FROM dbo.Tally  WHERE N <= LEN(@str1)
ORDER BY N

SELECT N, SUBSTRING(@str2,N,1)letters
INTO #b
FROM dbo.Tally  WHERE N <= LEN(@str2)
ORDER BY N

IF EXISTS(
SELECT A.*,B.* FROM
(
SELECT letters,COUNT(*)C FROM #a GROUP BY letters
)A
FULL OUTER JOIN
(
SELECT letters,COUNT(*)C FROM #b GROUP BY letters
)B
ON A.letters = B.letters AND A.C = B.C
WHERE A.letters IS NULL OR B.letters IS NULL
)
PRINT ‘NOT ANAGRAM’
ELSE
PRINT ‘ANAGRAM’


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.