Using Right and Left Function in SQL Server

Introduction

In this article, I provide a quick overview of using the right and left functions in SQL Server with some code examples. The examples are developed in SQL Server using the SQL Server Management Studio. So let's look at a practical example of using the right and left functions in SQL Server. 

The following are the queries to add the first and after numbers 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 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 the 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 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 the 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 the number before the String using the left function.

Example2

In this example, we take a string and a number. The number will be added to the left of the String using the left function.

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

Conclusion

This article taught us a quick overview of using the Right and Left functions in SQL Server.


Similar Articles