SQL Tutorial SQL Advanced SQL Database SQL References

MySQL RIGHT() Function



The MySQL RIGHT() function is used to extract a substring from a string, starting from the right-most character.

Syntax

RIGHT(string, number_of_chars)

Parameters

string Required. Specify the string to extract from.
number_of_chars Required. Specify the number of characters to extract. If this parameter exceeds the length of the string, this function will return string.

Return Value

Returns the substring extracted from specified string.

Example 1:

The example below shows the usage of RIGHT() function.

mysql> SELECT RIGHT('AlphaCodingSkills.com', 1);
Result: 'm'

mysql> SELECT RIGHT('AlphaCodingSkills.com', 4);
Result: '.com'

mysql> SELECT RIGHT('AlphaCodingSkills.com', 21);
Result: 'AlphaCodingSkills.com'

mysql> SELECT RIGHT('AlphaCodingSkills.com', 50);
Result: 'AlphaCodingSkills.com'

mysql> SELECT RIGHT('Alpha Coding Skills', 6);
Result: 'Skills'

Example 2:

Consider a database table called Employee with the following records:

PhoneNumberEmpIDAddress
+33-14XXXXX011Grenelle, Paris, France
+31-20XXXXX192Geuzenveld, Amsterdam, Netherlands
+86-10XXXXX4583Yizhuangzhen, Beijing, China
+65-67XXXXX44Yishun, Singapore
+81-35XXXXX725Koto City, Tokyo, Japan

In the query below, the RIGHT() function is used to exclude the country code from the PhoneNumber column records.

SELECT *, RIGHT(PhoneNumber, LENGTH(PhoneNumber) - 4) AS ContactNumber 
FROM Employee;

This will produce the result as shown below:

PhoneNumberEmpIDAddressContactNumber
+33-14XXXXX011Grenelle, Paris, France14XXXXX01
+31-20XXXXX192Geuzenveld, Amsterdam, Netherlands20XXXXX19
+86-10XXXXX4583Yizhuangzhen, Beijing, China10XXXXX458
+65-67XXXXX44Yishun, Singapore67XXXXX4
+81-35XXXXX725Koto City, Tokyo, Japan35XXXXX72

❮ MySQL Functions

5