Strings

RIGHT

Takes the given number of characters from the end of a string.

Syntax

RIGHT(<text>, <count>)

RIGHT(phone, 3) gives the last three characters. A negative count means “everything except the start”: RIGHT(<text>, -4) drops the first four characters. Its mirror function is LEFT, which takes characters from the start.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The last characters
SELECT RIGHT('PostgreSQL', 3) AS last_three;
last_three
SQL
The last digits of a phone number
SELECT name,
RIGHT(phone, 3) AS last_digits
FROM employees;
namelast_digits
Emma123
LiamNULL
Olivia456
Noah789
SophiaNULL
Everything except the start
SELECT RIGHT('ORD-00042', -4) AS number_part;
number_part
00042

We drop the four characters ORD- and keep the number.

Watch out

A negative count isn't an error — it means “everything except the first ones”: RIGHT('abc', -1) gives bc. If the count comes from an expression that happens to turn negative, there won't be an error.

A count larger than the length isn't an error either: RIGHT('SQL', 10) simply returns SQL.

Trailing spaces are characters too: in 'Emma ' the last character is a space. Remove them first with TRIM.

Related functions