Saturday, May 9, 2009

Mysql: Palindrome at SELECT query

Worked with palindrome terms at many languages. Now lets apply it at mysql select query. Lets we have a table called `info` having below structure.
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| dept | int(11) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+


And the values inside the table are,
+------------+------+------+
| name | id | dept |
+------------+------+------+
| madam | 1 | 0 |
| aaaaaaaa | 2 | 0 |
| a | 2 | 0 |
| aaaaa | 2 | 0 |
| aasaa | 2 | 0 |
| aaasaa | 2 | 0 |
| saa | 2 | 0 |
| palindrome | 2 | 0 |
| test | 2 | 0 |
+------------+------+------+


Now, lets write a SQL query, that will select only the name from info table which are palindrome. The sql query will be,
SELECT name FROM info WHERE name =  REVERSE(name);

And it will display you only the palindrome names.
+----------+
| name |
+----------+
| madam |
| aaaaaaaa |
| a |
| aaaaa |
| aasaa |
+----------+

For your information, Palindrome strings are string which are same if you reverse it. Thats why I have checked the name column, whether it is equal after reverse or not.

There are lots of method to detect the palindrome, but using reverse function, its the most easiest technique to detect palindromness of a given string.

1 comment:

coffee with nikhil said...

plz tell me without using reverse function in sql only

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...