RIGHT() in SQL
Extracts a specified number of characters from the end (right side) of a string.
Syntax
Return type
RIGHT() Function Example
What is RIGHT() in SQL?
The RIGHT()
function in SQL extracts a specified number of characters from the end (right side) of a string. It is useful for retrieving fixed-length identifiers, suffixes, or portions of text where the relevant data appears at the end. This function is primarily supported in SQL Server and some other databases, whereas MySQL and PostgreSQL achieve similar results using SUBSTRING()
. The RIGHT()
function is commonly applied in scenarios such as extracting file extensions, last digits of account numbers, or domain names from email addresses, making it valuable for text processing and data manipulation tasks.
Parameters:
string: The input string to extract from
number_of_characters: Number of characters to extract from the right
Example Use Cases:
-- Extract file extension
-- Get last four digits of credit card
-- Extract year from date string
Notes:
Behavior: Returns the entire string if the requested length exceeds the string length, an empty string for non-positive lengths, and includes spaces as characters.
Performance Considerations: Efficient for basic string operations
Version Info: Common function, but not available in all DBMS
Deprecated/Recommended Alternatives: SUBSTRING() is a universal alternative
Error Handling:
Error: Returns NULL if either parameter is NULL
Recommendation: Use COALESCE for NULL handling if needed
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
RIGHT()
RIGHT('Hello', 2)
Returns NULL
PostgreSQL
RIGHT()
RIGHT('Hello', 2)
Returns NULL
SQL Server
RIGHT()
RIGHT('Hello', 2)
Returns NULL
SQLite
RIGHT()
RIGHT('Hello', 2)
Returns NULL
BigQuery
RIGHT()
RIGHT('Hello', 2)
Returns NULL
Snowflake
RIGHT()
RIGHT('Hello', 2)
Returns NULL
Athena
RIGHT()
RIGHT('Hello', 2)
Returns NULL