AppDividend
Latest Code Tutorials

SQL Right Function Example

0

SQL Right Function is used for extracting a substring starting from the right, followed by the number of characters. The RIGHT() function extracts several characters from a string (starting from right). SQL RIGHT() function extracts the given number of characters from the right side of the specified character string.

So, if you are searching for a substring of the right part of the main string, then you can use the RIGHT() function.  It accepts two parameters the string and no. of characters we are looking for in the string.

SQL Right Function

See the syntax of the SQL Right function.

SELECT RIGHT (string, no_of_characters);

The function accepts two parameters.

Parameters

  1. String: The input string from which the substring will be extracted and can be a literal string, variable, or column.
  2. No_of_characters: The number of characters you wish to extract from the string.

The RIGHT() function returns the value of VARCHAR when the input_string is non-Unicode character data type and returns an NVARCHAR if the input_string is a Unicode character data type.

Query 1

SELECT RIGHT ('AppDividend.com', 3);

Output

'com'

Here 3 characters were displayed starting from the rightmost part of the string.

Query 2

SELECT RIGHT ('AppDividend.com', 4);

Output

'.com'

Here 4 characters were displayed starting from the rightmost part of the string.

Query 3

SELECT RIGHT ('SQL IS FUN', 4);

Output

' FUN'

Here 3 characters were displayed starting from the rightmost part of the string. Before FUN, there is whitespace, which is also counted as a character.

Query 4

SELECT RIGHT ('SQL IS FUN', 20);

Output

'SQL IS FUN'

Here the number of characters exceeded the length of the string as a whole result string is displayed as an output.

Let’s apply the RIGHT function in a Table.

Table: Employee

Emp_id First_name City State Phone
101 Rohit Patna Bihar 8585145852
201 Shivam Jalandhar Punjab 8958458785
301 Karan Allahabad Uttar Pradesh 9987845784
401 Suraj Kolkata West Bengal 8878989898
501 Akash Vizag Andhra Pradesh 9898547500

 

Now if we want to display the last 7 digits of the phone, then the following query has to be written:

Query

Select First_name AS Emp_Name, RIGHT (Phone, 7) AS Last_seven_digit 
from Employee;

Output

Emp_Name Last_seven_digit
Rohit 5145852
Shivam 8458785
Karan 7845784
Suraj 8989898
Akash 8547500

 

So, you can see that the last seven-digit of phone number is displayed under the column named Phone.

Finally, SQL Right Function Example is over.

Related Posts

SQL STR Function

SQL Space Function

SQL Rtrim Function

SQL Reverse Function

SQL Translate Function

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.