RIGHT()
SQL · String Functions
Theory
RIGHT(string, n) returns the last n characters of a string. RIGHT('9829012345', 4) returns '2345'. If n is longer than the string, the whole string comes back. It reads the string from the end, so it works even when values have different lengths, as long as the part you want has a fixed length at the end.
RIGHT is available in MySQL, SQL Server, Postgres and Snowflake but not in SQLite or Oracle. There, SUBSTR(string, -n) does the same job, because a negative start position counts from the end. A classic use is masking sensitive values: 'XXXXXX' || RIGHT(phone, 4) shows only the last four digits of a mobile number. Others are taking a fixed-length suffix such as a file extension or the last digits of an account number. Watch out for trailing spaces, especially in fixed-width CHAR columns: they count, so RTRIM the value first.
Why we use it
Many identifiers carry meaning at the end: last digits of a card or phone number, a check digit, a year suffix. RIGHT extracts them directly, which is perfect for masking data and for matching on suffixes.
When to use it
Use RIGHT when the part you need has a fixed length at the end of the string. In SQLite or Oracle use SUBSTR(str, -n). If the suffix length varies (like everything after the last dot), you need INSTR-style searching instead.
How it works
- Take the string and n
- n > string length? Yes: Return the whole string. No: Count n characters back from the end.
- Trailing spaces count as characters
- Return the suffix
Syntax
RIGHT(string, n)Example
SELECT RIGHT(email, 10) FROM employees;Key points
- Not available in SQLite or Oracle: use SUBSTR(str, -n)
- Returns the whole string if n exceeds its length
- Common for masking phone or account numbers
- Trailing spaces count: RTRIM fixed-width values first
- Great for fixed-length suffixes like extensions or check digits