SQL Server RIGHT() Function
In SQL Server, the RIGHT()
function is used to return the rightmost characters of a specified string.
In SQL Server, the RIGHT()
function is used to return the rightmost characters of a specified string. It can be used to extract a portion of a string by extracting a specified number of characters from the right-hand side of the string.
Syntax
RIGHT(string, length)
Where:
string
: Required. The string from which to extract characters from the right-hand side.length
: Optional. The number of characters to return fromstring
. If omitted, the function will return the entirestring
.
Use Cases
Here are some scenarios where the RIGHT()
function can be used:
- Extracting area codes or extension numbers from phone numbers
- Extracting file names or extensions from file paths
- Extracting year or month values from date strings
Examples
Here are two examples of using the RIGHT()
function:
Example 1
We have a table with employee names and phone numbers, and we need to extract the area code from the phone numbers:
SELECT RIGHT(Phone, 4) AS AreaCode, EmployeeName
FROM Employee
This will return a new result set with each employee’s name and the area code of their phone number.
Example 2
We have a table with file paths and need to extract the file name from the file path:
SELECT RIGHT(FilePath, CHARINDEX('\', REVERSE(FilePath))-1) AS FileName
FROM FileTable
In this example, the CHARINDEX()
and REVERSE()
functions are used to find the position of the last backslash character, and then the RIGHT()
function is used to extract the file name after the backslash.
Conclusion
The RIGHT()
function is a very useful function for extracting a portion of characters from a string. Whether it’s extracting from phone numbers, file paths, or date strings, the RIGHT()
function can easily accomplish the task.