The MySQL RIGHT is a string function, which extracts a specified number of characters from the right side of a string. Its syntax is as follows:
Syntax
RIGHT(str, length)
str: This is the input string from which you want to extract characters.
length: This parameter specifies the number of characters to extract from the right side of the string. It is an optional parameter, and if not provided, the function returns an empty string.
Example
SELECT RIGHT('MySQL RIGHT function', 8) AS Result;
This query would return:
function
In the example above, the RIGHT function extracts the last 8 characters from the input string ‘MySQL RIGHT function’, resulting in the output ‘function’.
Common Uses
Extracting File Extensions: The RIGHT function can be used to extract file extensions from filenames. For example, to extract the extension from the filename “image.png”, you can use the query:
SELECT RIGHT('image.png', 4);
This will return the substring “.png”, which is the file extension.
Limiting Results: The RIGHT function can be used to limit the number of characters displayed in a query result. For example, to display only the first three characters of a column named name, you can use the query:
SELECT RIGHT(name, 3) AS name_abbreviation FROM table_name;
This will create a new column named name_abbreviation that contains the first three characters of the name column.
Data Cleaning: The RIGHT function can be used to remove unwanted characters from the right side of a string. For example, to remove the trailing space characters from a string, you can use the query:
SELECT RIGHT(str, LENGTH(str) - 1) FROM table_name;
This will remove the trailing space characters and leave only the desired characters.
Keep in mind that the MySQL RIGHT function is case-sensitive, and the length parameter must be a positive integer. If the length is zero or negative, the function returns an empty string. If the length is greater than the length of the input string, the entire input string is returned.