PostgreSQL RIGHT() Function: Extract Characters From the Right of a String

PostgreSQL offers a variety of string functions to manipulate the strings data, such as the LENGTH() function, LOWER() function, REPLACE() function, etc. RIGHT() is one of the built-in string functions that extract the characters from the right of the targeted string. It can extract the “n” number of characters from a string, where n can be a positive or negative value.

This postgres blog demonstrates how to use the RIGHT() function in Postgres using various practical examples.

How Does the RIGHT() Function Work in PostgreSQL?

The RIGHT() function takes a string and the number of characters to extract as arguments and retrieves the extracted/modified string:

RIGHT(string, n);

The “n” represents the number of characters extracted from a string's right. It can be positive or negative. If the value of “n” is negative, then all the string characters will be extracted except the ‘n’ leftmost characters.

Example 1: Using the RIGHT() Function With a Positive Value of n

In the following query, we will extract the six characters from the rightmost of the given string using the RIGHT() function:

SELECT RIGHT('Hello! Welcome to Commandprompt', 6);
img

The output signifies that the RIGHT() function retrieves the six characters from the right of the input string.

Example 2: Using the RIGHT() Function With a Negative Value of n

The following statement illustrates how the RIGHT() function work if the “n” parameter has a negative value:

SELECT RIGHT('Hello! How are You', -6);
img

The output indicates that the RIGHT() function retrieves all the characters from a string except the six leftmost characters.

Example 3: Extracting Specific Records Via the RIGHT() Function

We have created a sample table named “staff_info” with the following data:

img

Now we will utilize the RIGHT() function to extract all those employees whose name ends with “e”:

SELECT staff_name, staff_designation
FROM staff_info 
WHERE RIGHT(staff_name, 1)='e';
img

The output demonstrates that the RIGHT() function retrieves the details of all those staff members whose names end with “e”.

This is how you can use the RIGHT() function in Postgres.

Conclusion

The RIGHT() function takes a string and the number of characters to extract as arguments and retrieves the extracted/modified string. It can extract the “n” number of characters from a string, where n can be a positive or negative value. If the value of “n” is negative, then all the string characters will be extracted except the “n” leftmost characters. This post explained the usage of the RIGHT() function using practical examples.