SQL RIGHT() Function

SQL RIGHT() function returns substring from right side of specified string from a given column. If any column cell contains NULL value then it returns output as NULL for that value.

Syntax

SELECT RIGHT (String, IntegerValue)

Below is a simple example for RIGHT() function where we are selecting four characters from left side of given string.

SELECT RIGHT('SQLServerLog', 3)

Right0

Now, we will consider examples from Student table.

avg

Here we will select three characters from right side of FirstName column with below query.

SELECT RIGHT(FirstName, 3) AS NewColumn, FirstName FROM Student

Right1

As you can see, we have extracted right three characters from FirstName column with RIGHT() function. Similarly you can add more columns and add paddings to represent as code. We will see one more query.

SELECT 'XXXX' + RIGHT(FirstName, 3) + CAST(RollNumber AS varchar) 
     + 'XXXX' AS CODE FROM StudentĀ 

Here, we are selecting three characters from right side of FirstName column with RollNumber column and padding with ‘XXXX’ value on both side with new column name as CODE.

Right2

Reference: Manzoor Siddiqui [www.SQLServerLog.com]

You may also like...

Leave a Reply

Your email address will not be published.