SQL Server RIGHT() Function
The RIGHT()
function in SQL Server extracts a specified number of characters from the right-hand side of a string. This is a very useful function for extracting specific parts of text data, such as postal codes from addresses or file extensions from filenames.
RIGHT(): Definition and Usage
RIGHT()
is designed to grab a substring from the end of a string. Unlike functions that start extracting from the beginning of a string, `RIGHT()` begins from the rightmost character. If you ask for more characters than exist, 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 side. If this is greater than the length of the string, the entire string is returned. This is required. |
Examples
Extracting Characters from a Literal String
This example extracts the last three characters ("ial") from the string 'SQL Tutorial'.
Syntax
SELECT RIGHT('SQL Tutorial', 3) AS ExtractString;
Output
rial
Extracting Characters from a Column
This example extracts the last five characters from the 'CustomerName' column in the 'Customers' table (assuming a table named 'Customers' exists with a 'CustomerName' column).
Syntax
SELECT RIGHT(CustomerName, 5) AS ExtractString
FROM Customers;
Output
ExtractString
-------------
(The last five characters of each CustomerName will be displayed here.)
Extracting More Characters Than Exist
If you try to extract more characters than exist, the entire string is returned.
Syntax
SELECT RIGHT('SQL Tutorial', 100) AS ExtractString;
Output
SQL Tutorial