Return the rightmost n characters of the input string.
RIGHT(str, n)
## Overview Returns the rightmost `n` characters of the input string. RIGHT is the mirror of LEFT and provides a concise way to extract a suffix of fixed length. Common uses include reading the last four digits of an identifier, extracting a file extension, and slicing a trailing checksum. RIGHT supports a negative-length idiom: RIGHT(s, -k) returns everything except the first `k` characters, useful for stripping a known-length prefix such as 'https://' or a country code. ## Behavior - Returns NULL when the input string is NULL. - Returns NULL when `n` is NULL. - If `n` is 0, returns an empty string. - If `n` is greater than or equal to the character length of the string, returns the full string. - If `n` is negative, returns all characters except the first |n|. If |n| is greater than the string length, returns an empty string. - Counts Unicode code points, so multi-byte UTF-8 characters each count as one position. - Never raises an error for out-of-range `n`. ## Compatibility - Widely supported across SQL dialects with the same positive-n semantics. - The negative-n convention is equivalent to SUBSTRING(str, |n| + 1, CHAR_LENGTH(str)).
| Name | Type | Description |
|---|---|---|
str | Specifies the input string from which trailing characters are extracted. | |
n | Specifies the number of characters to return from the right. Values greater than the string length return the full string. Negative values return all but the first |n| characters. Zero returns an empty string. |
-- Last 3 characters
SELECT RIGHT('hello', 3); -- 'llo'
-- n greater than length returns the full string
SELECT RIGHT('hi', 10); -- 'hi'
-- Zero returns empty string
SELECT RIGHT('hello', 0); -- ''
-- Negative n excludes the first |n| characters
SELECT RIGHT('hello', -2); -- 'llo'
-- Get the last 4 digits of a card number column (for masking display)
SELECT RIGHT(card_last4_raw, 4) AS last4
FROM retail.customers.profiles;
-- NULL propagates
SELECT RIGHT(CAST(NULL AS VARCHAR), 3); -- NULL