Reader Level:
Articles

Using Right and Left Function in SQL Server

By Rohatash Kumar on April 01, 2013
In this article I provide a quick overview of how to use the right and left functions in SQL Server.
  • 0
  • 0
  • 13646

In this article I provide a quick overview of how to use the right and left functions in SQL Server. In this article you will see some examples related to the left and right functions. So let's have a look at a practical example of how to use the right and left functions in SQL Server. The examples are developed in SQL Server 2012 using the SQL Server Management Studio. 

The following are the queries to add the first and after number in a string.

Using the SQL Left Function

The Left string function takes two arguments. The first argument is a string value and the second argument is an integer value specifying the length. It returns the first characters of the specified length starting from the left side of the string entered as the first argument.

Syntax

The syntax of the LEFT() function is as follows:

LEFT(String, NumberOfCharacters) RETURNS varchar;

Example1

Declare @Name varchar(20)-- Declare a char Variable

Set @Name='Rohatash' 

selectLeft(@Name,3)

Output

SQL-Left-Function.jpg

The example below defines Number before the String using the left function.

Example2

In this example we take a string and a number. Using the left function a number will be added to the left of the string.

Declare @Name varchar(20)-- Declare a char Variable

Set @Name='Rohatash' -- Name

Declare @Number int   -- Declare a int Variable

set @Number=123 -- Number to add in String

selectleft(@Number,3)+ @Name  -- Using left Function

Output

SQL-Left-Function-example.jpg

 

Using the SQL Right Function

The Right string function takes two arguments. The first argument is a string value and the second argument is an integer value specifying the length. It returns the last characters of the specified length starting from the right side of the string entered as the first argument.

Syntax

The syntax of RIGHT() function is as follows :

RIGHT(String, NumberOfCharacters) RETURNS varchar

Example1

Declare @Name varchar(20)-- Declare a char Variable

Set @Name='Rohatash' 

selectRight(@Name,3)

Output

SQL-RightFunction.jpg

The example below defines Number before the String using the left function.

Example2

In this example we take a string and number. Using the left function the number will be added to the left of the string.

Declare @Name varchar(20)-- Declare a char Variable

Set @Name='Rohatash' -- Name

Declare @Number int   -- Declare a int Variable

set @Number=123 -- Number to add in String

select @Name + Right(@Number,3)  -- Using right Function

Output

SQL-RightFunction-example.jpg

 

Rohatash Kumar

Normal 0 false false false EN-AU X-NONE X-NONE I am a Microsoft .NET software Developer and author and C# Corner MVP. I hold Masters degree i... Read more

COMMENT USING

Trending up