I am going to continue my series of very short articles or tidbits on Transaction SQL string functions. I will exploring the REVERSE() function today.
The REVERSE() function takes a source string as input and returns each character in the reverse order as output. Therefore, the last character input string is now the first character in the output string. And the first character in the input string is last character in the output string.
Let’s have some fun by using palidromes in the next example. The example below has two words that become other words when reverse. This is usually not the case. Most of the time, a reversed word is gibberish.
1 2 3 4 5 |
-- Palindromes 1 select 'stressed' as forward, reverse('stressed') as backward -- Palindromes 2 select 'star' as forward, reverse('star') as backward |
1 2 3 4 5 6 7 8 9 |
output: forward backward -------- -------- stressed desserts forward backward ------- -------- star rats |
One thing to always worry about when using TSQL functions is how will it react with a EMPTY strings or NULL values? Both empty strings and NULL values as input return themselves as output.
1 2 3 4 5 |
-- Empty string returns empty string select reverse('') as str_word -- Null returns Null select reverse(NULL) as str_word |
1 2 3 4 5 6 7 8 |
output: str_word -------- str_word -------- NULL |
Next time, I will be exploring the RIGHT() function.