MySQL RIGHT() Function with Examples

How to Use the MySQL RIGHT() Function

In this tutorial, you'll learn how to use the MySQL RIGHT() function. RIGHT() returns a specified number of characters from the right of a given string.

MySQL RIGHT() Syntax

The syntax of the RIGHT() function is as follow:

RIGHT(string, length)

Remarks

  • The function returns NULL if either string or length is NULL.
  • If you want to extract characters from the left of a given string, use the LEFT() function.
  • Use the SUBSTRING() function if you want to extract characters from the string, starting at the specified position.

Examples

Example 1

The following statement extracts 30 characters from the right of the string:

SELECT RIGHT("If you want to learn more, here is the list of MySQL tutorials", 30) AS SubString;

Result:

is the list of MySQL tutorials

Example 2

The following table is our demo customers table:

customer_idcustomer_codecustomer_namecountry
11#CID_50010Josh WarnerJapan
12#CID_50011Lisa RamseyJapan
13#CID_50012Clifton ChristensenJapan
14#CID_50013Iris WilkersonUnited State
15#CID_50014Charles HarmonJapan
16#CID_50015Glen WoodUnited State
17#CID_50016Francis LewisGermany
18#CID_50017William BarnettGermany

The following statement extracts 6 characters from the left of the text in the customer_name column:

SELECT customer_name, RIGHT(customer_name, 6) AS ExtractCustomerName
FROM customers
WHERE country = "Japan";

Result:

customer_name ExtractCustomerName
Josh WarnerWarner
Iris Wilkersonkerson
Glen Woodn Wood

Example 3

The following statements all return NULL:

SELECT RIGHT(NULL, 4) AS SubString;

SELECT RIGHT(NULL, NULL) AS SubString;

SELECT RIGHT("If you want to learn more, here is the list of SQL tutorials", NULL) AS SubString;

As mentioned above, if either of both arguments is NULL, RIGHT() returns NULL.

In this tutorial, you've learned how to use the MySQL RIGHT() function to extract a specified number of characters from the right of a given string. If you want to extract characters from the left of the string, use the LEFT() function instead. And in some cases, you want to extract characters from the string starting at the specified position, then you can use the SUBSTRING() function.


See also:
MySQL LIKE Operator Pattern Matching and Examples
MySQL SUBSTRING_INDEX Function with Examples
MySQL EXISTS Operator with Examples
MySQL ROW_NUMBER Function with Examples
MySQL CONCAT() Function | Concatenate Strings in MySQL

Leave a Comment