How to Select a Certain Number of Characters from the Left or Right of a String in SQL Server

If you ever find yourself wanting only the first part of a string, or the last part of it, this article might help.

This article is specific to SQL Server, but the functionality is pretty common across most/all database management systems, not to mention most programming languages.

When working with SQL Server, you can use theT-SQL LEFT() and RIGHT() functions to return any given number of characters from the left or right of a string.

Syntax

The official syntax for both functions goes like this:

RIGHT ( character_expression , integer_expression )
LEFT ( character_expression , integer_expression )

Where character_expression is the string, and integer_expression is the number of characters you want to return from that string.

Example

Here’s an example of selecting the 5 leftmost characters from a string:

SELECT LEFT('marshmallow', 5);

Result:

marsh

And here’s an example of selecting the 5 rightmost characters from that same string:

SELECT RIGHT('marshmallow', 5);

Result:

allow

Database Example

Of course, when using SQL Server, you’ll mostly be working with data in a database. Here’s an example of using the LEFT() and RIGHT() functions on data returned from a database.

LEFT()

USE Music;
SELECT TOP 5
    AlbumName AS Original, 
    LEFT(AlbumName, 5) AS Modified
FROM Albums;

Result:

Original                Modified
----------------------  --------
Powerslave              Power   
Powerage                Power   
Singing Down the Lane   Singi   
Ziltoid the Omniscient  Zilto   
Casualties of Cool      Casua   

RIGHT()

USE Music;
SELECT TOP 5
    AlbumName AS Original, 
    RIGHT(AlbumName, 5) AS Modified
FROM Albums;

Result:

Original                Modified
----------------------  --------
Powerslave              slave   
Powerage                erage   
Singing Down the Lane    Lane   
Ziltoid the Omniscient  cient   
Casualties of Cool       Cool