The RIGHT() function in MySQL is used to extract a specified number of characters from the right side of a string.
Syntax
RIGHT(string, number_of_chars)
Parameters
| Parameter | Description |
|---|---|
string |
Required. The string to extract characters from. |
number_of_chars |
Required. The number of characters to extract. If this number exceeds the length of the string, the entire string will be returned. |
Definition and Usage
- The
RIGHT()function extracts a specified number of characters starting from the right side of a string. - It is useful when you need to retrieve the last few characters of a string.
Usage Examples
Example 1: Extracting Characters from the Right Side
Extract the last 4 characters from the string "SQL Tutorial is cool":
SELECT RIGHT("SQL Tutorial is cool", 4) AS ExtractString;
Output:
| ExtractString |
|---|
| cool |
Explanation: The function extracts the last 4 characters ("cool") from the string "SQL Tutorial is cool".
Example 2: Extracting from the CustomerName Column
Extract the last 5 characters from the CustomerName column in the Customers table:
SELECT RIGHT(CustomerName, 5) AS ExtractString
FROM Customers;
Output:
| ExtractString |
|---|
| erName |
| hnson |
| nson |
Explanation: For each row, the function extracts the last 5 characters of the CustomerName column.
Technical Details
- Works In: From MySQL 4.0 onwards.
- Return Type: The function returns a substring containing the specified number of characters from the right side of the string.
- Behavior: If
number_of_charsexceeds the length of the string, the entire string is returned. Ifnumber_of_charsis0, an empty string is returned.
Applications
- Retrieving Last Few Characters: Useful in situations where you need to extract trailing data, such as file extensions or domain suffixes.
- String Manipulation: Can be combined with other functions like
LEFT()orSUBSTRING()for complex string processing. - Database Formatting: Helpful when formatting or displaying data in a specific way, such as showing the last digits of a serial number.
Example Use Case
If you want to retrieve the last 4 digits of a phone number stored in a column PhoneNumber:
SELECT RIGHT(PhoneNumber, 4) AS LastFourDigits
FROM Contacts;
This would return the last four digits of each phone number stored in the PhoneNumber column.
Key Notes
- The
RIGHT()function is the opposite of theLEFT()function, which extracts characters starting from the left side of a string. - It is an effective tool when dealing with data that requires the last part of the string, such as extracting file extensions, product codes, or suffixes.