SQL Server REVERSE String Function with Examples 2008, R2, 2012, 2014

The SQL Server REVERSE string function can be quite useful if you need to return a string or sequence in reverse order.  It can also be quite powerful when used in combination of other SQL keywords (CHARINDEX, RIGHT).  We’ll start by looking at some of the simple uses.

[Sarcasm to follow]

So say you’re an android and you’ve always dreamed of reversing your name and have gone your whole life up to this point just waiting to be able to do it in SQL.  Today is your lucky day!  The code below will magically turn your name into its REVERSE version.

SELECT REVERSE('COMMANDER DATA');
--------------
ATAD REDNAMMOC

(1 row(s) affected)

Fantastic.  This could also assist you if  you’re anticipating getting pulled over by the cops for a sobriety test and can’t quite remember how to say the alphabet backwards.

REVERSE can also flip number sequences!  This works, of course, because SQL Server converts the numbers to a varchar first.

SELECT REVERSE(1234567890);
------------
0987654321

(1 row(s) affected)

Ok. Ok.  Not impressed I see.  Then perhaps you’re a word nerd and are big into palindromes.  We can use the SQL Server REVERSE function to help us determine if a word is a palindrome like so…

DECLARE @palindromeTest VARCHAR(100) = 'RACECAR';
IF(@palindromeTest = REVERSE(@palindromeTest))
	SELECT 'THIS IS A PALINDROME!';
ELSE
	SELECT 'THIS IS NOT A PALINDROME';
--------------------
THIS IS A PALINDROME

(1 row(s) affected)

Note that in SQL Server 2008+ you can declare and set a variable in one line.

Still not impressed.  Maybe you are a serious nerd and are into DNA sequencing.  Often times you’ll need to find the reverse, complement, or reverse-complement of a DNA sequence.  While REVERSE won’t help you with the complement portion of the problem, it will certainly help you reverse your sequence.

-- REVERSE A DNA SEQUENCE
DECLARE @dnaSequence VARCHAR(100) = 'GGGatttataaaaaata';
SELECT REVERSE(@dnaSequence);
-----------------
ataaaaaatatttaGGG

(1 row(s) affected)

Pretty amazing stuff.

Now, going for broke, I’ll be providing a few more complex examples of REVERSE and a useful UDF (user defined function) to make things a bit more convenient.

The last couple of scenarios I want to cover is when you need to pull a filename off the end of a URL and full or absolute path.  The technique is identical for all cases as shown below.  I incorporated both examples into one to show the similarities.

-- GET THE FILENAME FROM URL
-- GET THE FILENAME FROM A FULL PATH
DECLARE @URL VARCHAR(1000);
DECLARE @FULLPATH VARCHAR(1000)
DECLARE @URLFILENAME VARCHAR(100);
DECLARE @FULLPATHFILENAME VARCHAR(100);

SET @URL = 'HTTP://EXAMPLESQL.COM/SQL-RESOURCES/RESOURCE.PHP';
SET @FULLPATH = '/HOME/FTP/CLIENTS/ACME/TEST.TXT';

-- THESE ARE EXACTLY THE SAME!
-- YOU MIGHT MAKE A USER DEFINED FUNCTION (UDF) TO DO THIS IF YOU PLAN ON USING IT A BUNCH
-- BUT BE AWARE THAT A CALL TO A UDF DOES CAUSE A PERFORMANCE DECREASE
SET @URLFILENAME = RIGHT(@URL, CHARINDEX('/', REVERSE(@URL))-1);
SET @FULLPATHFILENAME = RIGHT(@FULLPATH, CHARINDEX('/', REVERSE(@FULLPATH))-1);

SELECT @URLFILENAME;
SELECT @FULLPATHFILENAME;

GO
------------
RESOURCE.PHP

(1 row(s) affected)

---------
TEST.TXT

(1 row(s) affected)

Lastly, I wanted to show everyone a helpful UDF that will essentially encapsulate the magic above into a single callable function.

IF EXISTS(SELECT 1 FROM sys.sysobjects WHERE id = OBJECT_ID(N'udfGetFilenameFromPathOrUrl') AND xtype IN (N'FN', N'IF', N'TF'))
	DROP FUNCTION udfGetFilenameFromPathOrUrl;
GO

CREATE FUNCTION udfGetFilenameFromPathOrUrl(
	@PATHVAR VARCHAR(1000),
	@DELIMITER CHAR(1)	
)
RETURNS VARCHAR(200)
BEGIN
	RETURN RIGHT(@PATHVAR, CHARINDEX(@DELIMITER, REVERSE(@PATHVAR))-1);;
END
GO

And using the function…

DECLARE @URL VARCHAR(1000) = 'HTTP://EXAMPLESQL.COM/SQL-RESOURCES/RESOURCE.PHP';
SELECT dbo.udfGetFilenameFromPathOrUrl(@URL, '/');
-------------
RESOURCE.PHP

(1 row(s) affected)

So there you have it.  The SQL Server REVERSE function can be useful as we can see from the examples above.  Be careful how you wield this power though.  😉

Valid for SQL Server  2008, 2008 R2, 2012, 2014.

SQL Server 2012 String Functions List

Hi Everyone.  In this post I’m simply listing off all SQL Server 2012 string functions alphabetically for quick reference.  In all, there are 25 keywords in the list.

SQL Server 2012 String Functions

ASCII
CHAR
CHARINDEX
CONCAT
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
UNICODE
UPPER

How to use the SQL Server RIGHT string function with T-SQL Examples 2005, 2008, R2, 2012, 2014

SQL Server RIGHT function code

The SQL Server RIGHT string function gives us the ability to return a given number of characters from a string on its rightmost side.  For example, say we have the text ‘Bill Jones’.  We can use the RIGHT function to return ‘Jones’ without having to parse the string from the beginning.  Let’s look at some code…

RIGHT ( string , int )

The code above is the syntax of the RIGHT function.  The first parameter is a string and the second is an integer letting sql server know how many rightmost characters you want from the string in the first parameter.  Let’s go back to our initial example from above…

SELECT RIGHT ('Bill Jones', 5);

The result of this query are:

Jones

Pretty simple stuff.  To use the SQL Server RIGHT function in a more practical way we might use it with a table.  So, let’s define a table called Document and fill it with some sample filenames.  We’ll then use the RIGHT and LEFT functions to help us fill in the extension for each file.

-- create the document table
CREATE TABLE Document (
Filename VARCHAR(50),
Extension VARCHAR(10)
);

-- insert the demo rows into the document table
INSERT INTO Document ([Filename]) VALUES ('family.jpg');
INSERT INTO Document ([Filename]) VALUES ('lessons.docx');
INSERT INTO Document ([Filename]) VALUES ('schemas.xml');
INSERT INTO Document ([Filename]) VALUES ('report.ps');
INSERT INTO Document ([Filename]) VALUES ('puppies.report');
INSERT INTO Document ([Filename]) VALUES ('secret.password');

-- get extension column size - this is a bit advanced since 
-- we are looking at the table's meta data to set our max
-- column size.  the query below works whenever you don't 
-- know the column size ahead of time and need to find it
-- dynamically.  
DECLARE @extensionColumnSize INT;
SELECT @extensionColumnSize = character_maximum_length    
    FROM information_schema.columns  
    WHERE TABLE_NAME = 'Document' AND COLUMN_NAME = 'Extension';

-- get the extension for each filename
DECLARE @i INT;
SET @i = 1;
WHILE @i < @extensionColumnSize
BEGIN
   UPDATE Document
   SET [Extension] = RIGHT([Filename], @i-1) FROM Document a
   WHERE (LEFT(RIGHT([Filename], @i),1)) = '.';

   SET @i = @i + 1;
END

-- table extensions should be filled in now
SELECT * FROM Document;

-- clean up by dropping/deleting table
DROP TABLE Document;

The first part of the example simply creates the Document table and fills it with six rows of data.  The second part is the juicy stuff.  First we find the maximum possible length of  an extension by getting the size of the Extension column from the database meta data.  Next, we loop from 1 to Extension column size which, in this case, is 10.  Each time through the loop we get the rightmost @i letters and check to see if a period is on the leftmost part of the string.  If it is a period then we update the Extension column with the rightmost @-1 characters (we don’t save the period).

I’ll admit that the example is not very simple.  However, you could ‘simplify’ the code above  as above but replacing lines 15-35 with the following…

UPDATE Document SET [Extension] = RIGHT([Filename], CHARINDEX('.', REVERSE([Filename]))-1);

It’s actually quite funny how much less code it takes.  The good thing with that one liner is that we don’t have to loop and deal with all kinds of variables and system tables but we do have to know about CHARINDEX and REVERSE…two more sql server functions.  I’ll be discussing those in later posts.  I think the first example, while perhaps a bit contrived, does provide some code that you might be able to repurpose for your own uses.  I cheated a little as well by also using the SQL Server LEFT function but you’ll find that they can be used together quite powerfully.

The results of the running code (either method) are below.

Filename                                           Extension
-------------------------------------------------- ----------
family.jpg                                         jpg
lessons.docx                                       docx
schemas.xml                                        xml
report.ps                                          ps
puppies.report                                     report
secret.password                                    password

So thats the SQL Server Right function and hopefully the example above will give you some ideas of your own on how to use it.

Valid for SQL Server 2005, 2008, R2, 2012, 2014

Happy coding!