![]() |
VOOZH | about |
The PostgreSQL RIGHT() function, allows you to extract a specified number of characters from the right side of a string. This function can be incredibly useful for various text-processing tasks.
Let us get a better understanding of the RIGHT Function in PostgreSQL from this article.
RIGHT(string, n)Let's analyze the above syntax:
Let us take a look at some of the examples of the RIGHT Function in PostgreSQL to better understand the concept.
The following statement can be used to query for the last character in the string 'XYZ'.
Query:
SELECT RIGHT('XYZ', 1);Output:
👁 PostgreSQL RIGHT Function ExampleExplanation: In this example, the RIGHT() function takes the string 'XYZ' and the integer 1 as arguments. It returns the last character of the string, which is 'Z'.
The following query uses the RIGHT() function in WHERE clause to get all customers whose last names ended with 'son' in the customer table of the sample database.
Query:
SELECT last_name FROM customer WHERE RIGHT(last_name, 3) = 'son';
Output:
👁 PostgreSQL RIGHT Function ExampleExplanation: In this query, the RIGHT() function is used within the WHERE clause to filter the customer table. It extracts the last three characters of each 'last_name' and compares them to 'son'. The query returns all rows where the last three characters of the 'last_name' match 'son'.
- The RIGHT() function does not support negative values for the 'n' parameter.
- The RIGHT() function works not only with text and character strings but also with other data types that can be implicitly cast to text, such as 'varchar' and 'char'.
- If the 'n' value is greater than the length of the string, RIGHT() will return the entire string without raising an error.
- Trailing spaces in strings are preserved when using RIGHT(). If you need to remove trailing spaces, combine RIGHT() with the TRIM()function.