PostgreSQL RIGHT() Function
Summary: in this tutorial, you will learn how to use the PostgreSQLRIGHT() function to return the lastn characters in a string.
Introduction to the PostgreSQL RIGHT() function
TheRIGHT() function allows you to retrieve the last n characters of a string.
Here’s the basic syntax of theRIGHT() function:
RIGHT(string, n)The PostgreSQLRIGHT() function requires two arguments:
stringis a string from which a number of the rightmost characters are returned.nis a positive integer that specifies the number of the rightmost characters in the string that should be returned.
TheRIGHT() function returns the lastn characters in a string. Ifn is negative, theRIGHT() function returns all characters in the string but first|n| (absolute) characters.
If you want to return then first characters of a string, you can use theLEFT() function.
PostgreSQL RIGHT() function examples
Let’s take some examples of using the PostgreSQLRIGHT() function.
1) Basic PostgreSQL RIGHT() function example
The following statement uses theRIGHT() function to get the last character in the string'XYZ':
SELECT RIGHT('XYZ',1);Here is the result:
right------- Z(1 row)To get the last two characters, you pass the value2 as the second argument as follows:
SELECT RIGHT('XYZ', 2);Output:
right------- YZ(1 row)The following statement illustrates how to use a negative integer as the second argument:
SELECT RIGHT('XYZ', - 1);In this example, theRIGHT() function returns all characters except for the first character.
right------- YZ(1 row)2) Using the RIGHT() function with table data example
See the followingcustomer table in thesample database:
The following statement uses theRIGHT() function inWHERE clause to get all customers whose last names end with 'son':
SELECT last_nameFROM customerWHERE RIGHT(last_name, 3) ='son';Output:
last_name------------- Johnson Wilson Anderson Jackson Thompson...Summary
- Use the PostgreSQL
RIGHT()function to get the n rightmost characters in a string.
Last updated on