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_id | customer_code | customer_name | country |
---|---|---|---|
11 | #CID_50010 | Josh Warner | Japan |
12 | #CID_50011 | Lisa Ramsey | Japan |
13 | #CID_50012 | Clifton Christensen | Japan |
14 | #CID_50013 | Iris Wilkerson | United State |
15 | #CID_50014 | Charles Harmon | Japan |
16 | #CID_50015 | Glen Wood | United State |
17 | #CID_50016 | Francis Lewis | Germany |
18 | #CID_50017 | William Barnett | Germany |
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 Warner | Warner |
Iris Wilkerson | kerson |
Glen Wood | n 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.