MySQL RIGHT() Function
The RIGHT()
function in MySQL extracts a specified number of characters from the right-hand side of a string. It's a handy tool for extracting specific parts of text data, such as postal codes from addresses or file extensions from filenames.
RIGHT(): Definition and Usage
This function is useful for grabbing a substring from the end of a longer string. Unlike functions that start extracting from the beginning, RIGHT()
begins its extraction from the rightmost character. If you request more characters than are available, it simply returns the entire string.
Syntax
Syntax
RIGHT(string, number_of_chars)
Parameter Values
Parameter | Description |
---|---|
string |
The string from which you want to extract characters. This is required. |
number_of_chars |
The number of characters to extract from the right. If this exceeds the string length, the entire string is returned. This is required. |
Examples
Extracting Characters from a Literal String
This example extracts the last four characters ("cool") from the string "SQL Tutorial is cool".
Syntax
SELECT RIGHT("SQL Tutorial is cool", 4) AS ExtractString;
Output
cool
Extracting Characters from a Column
This example extracts the last five characters from the 'CustomerName' column in a table named 'Customers' (assuming this table and column exist).
Syntax
SELECT RIGHT(CustomerName, 5) AS ExtractString
FROM Customers;
Output
ExtractString
-------------
(The last 5 characters of each CustomerName from the Customers table)