PostgreSQL right() Function

The PostgreSQL right() function extracts the rightmost specified number of characters in the specified string and returns returns them as a string.

If you want to extract a certain number of characters from the left of a string, use the left() function.

right() Syntax

This is the syntax of the PostgreSQL right() function:

right(str, num)

Parameters

str

Required. The string where to extract characters.

num

Required. The number of characters to extract. It can be positive or negative. If it is negative, the right() function returns all characters except for the leftmost -num characters.

Return value

The PostgreSQL right() function returns the rightmost num characters of the string str.

If num is negative, the right() function returns all characters except for the leftmost -num characters.

The right() function will return str if num is greater than the length of str.

If num equals 0, the right() function will return empty ''.

If the parameter is NULL, the function will return NULL.

right() Examples

This example shows how to use the left() function to get the rightmost 2 characters of the string hello.

SELECT right('hello', 2) AS "right('hello', 2)";
 right('hello', 2)
-------------------
 lo

You can provide a negative number for num:

SELECT right('hello', -3) AS "right('hello', -3)";
 right('hello', -3)
--------------------
 lo

Here, since num is -3, the characters other than the leftmost 3 characters are returned. That is: lo.