MySQL RIGHT() function
RIGHT() function
MySQL RIGHT() extracts a specified number of characters from the right side of a string.
This function is useful in -
- Leading character removal: LTRIM() removes certain characters from the left side of a string.
- Data cleaning: LTRIM() is often used to remove spaces from strings at the beginning.
Syntax:
RIGHT(str, len)
Arguments:
Name | Description |
---|---|
str | A string from whose right side a number of characters are to be extracted. |
len | An integer indicating the number of characters to be extracted from str. |
Note: This function is multi-byte safe.
Syntax Diagram:
MySQL Version: 8.0
Pictorial Presentation:
Example of MySQL RIGHT() function
The following MySQL statement returns the rightmost 8 characters for the given string ‘w3resource’.
Code:
SELECT RIGHT('w3resource',8);
Output:
mysql> SELECT RIGHT('w3resource',8); +-----------------------+ | RIGHT('w3resource',8) | +-----------------------+ | resource | +-----------------------+ 1 row in set (0.00 sec)
Using RIGHT() with a longer string and a number larger than the string length
The following MySQL statement the function returns the whole string if the number of characters to extract is greater than the length of the original string.
Code:
SELECT RIGHT('w3resource', 15);
Output:
RIGHT('w3resource', 15)| -----------------------+ w3resource |
Using RIGHT() with NULL values
The following MySQL statement returns NULL if the original string is NULL.
Code:
SELECT RIGHT(NULL, 4);
Output:
RIGHT(NULL, 4)| --------------+ |
Example of MySQL RIGHT() function using table
The following MySQL statement returns the rightmost 7 characters from the column ‘aut_name’ in the table author for those rows, which have the column value of ‘country’ is ‘UK’.
Code:
SELECT aut_name,
RIGHT(aut_name,7)
FROM author
WHERE country='UK';
Sample table: author
Output:
mysql> SELECT aut_name, -> RIGHT(aut_name,7) -> FROM author -> WHERE country='UK'; +-----------------+-------------------+ | aut_name | RIGHT(aut_name,7) | +-----------------+-------------------+ | William Norton | Norton | | William Anthony | Anthony | | Piers Gibson | Gibson | | C. J. Wilde | . Wilde | +-----------------+-------------------+ 4 rows in set (0.00 sec)
Video Presentation
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mysql/string-functions/mysql-right-function.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics