PostgreSQL String Functions
PostgreSQL is a very powerful object-relational database management system. It provides a large number of functions and operators for the built-in data types, thereby relieving the developers from simpler tasks and focusing on the solution to the bigger problem. One such category of built-in functions is the PostgreSQL string functions. String formatting such as concatenation, displaying in a certain format, inserting/deleting substrings, etc. can sometimes be a tedious task. PostgreSQL string functions take care of that for you.
PostgreSQL has many functions which are not defined in the standard SQL functions. This provides the developers with a vast horizon of functions which can leverage to solve the bigger problem.
To illustrate various PostgreSQL String functions, we first need to create a database. The following database will be referred to in all the examples:
Examples of String Functions in PostgreSQL
String function is easy to use. Here we will discuss how to use string function in PostgreSQL
programming with the help of examples
Returns the ASCII value of the leftmost character of the string str.
SELECT FirstName, ASCII(FirstName) from Person
Returns the length of the string str in bits.
SELECT FirstName, BIT_LENGTH(FirstName) from Person
3. CHAR_LENGTH(str) / CHARACTER_LENGTH(str)
Returns the length of the string str in characters.
SELECT FirstName, CHAR_LENGTH(FirstName) from Person
4. CONCAT(str1, str2, …., strn)
Returns a string formed by joining str1 to strn. NULL arguments are ignored.
4.5 (1,207 ratings)
SELECT FirstName, LastName, CONCAT(FirstName, LastName) as DisplayName from Person
5. str1 || str2 ||…|| non-str ||…|| strn
Concatenates str1, str2 to strn and even non-string arguments.
SELECT Id || FirstName || LastName || phone || address as Concat_All from Person
Capitalizes the string, i.e. each word’s first letter is upper-cased and rest are lower-cased. Words are determined by non-alphanumeric separators.
Select INITCAP('This is a PostgreSQL example.')
7. LOWER() and UPPER()
Converts a string to lower case and upper case.
SELECT FirstName, LOWER(FirstName) as Lower, UPPER(FirstName) as Upper from Person
8. LEFT(str, len) / RIGHT(str, len)
Returns the leftmost and rightmost len characters from the string str. When len is negative, it returns the string str except for the leftmost or rightmost len characters.
SELECT FirstName, LastName, CONCAT(LEFT(LastName, 3), RIGHT(FirstName, 2)) as LoginID from Person
9. LENGTH(str) / LENGTH(str, encoding)
Returns the length of the string str in characters. This is unlike the operation of Length function in the SQL though. When specified, encoding provides the length in the particular encoding.
SELECT FirstName, LENGTH(FirstName), CHAR_LENGTH(FirstName) from Person
Calculates the length of the string str in bytes.
SELECT FirstName, LENGTH(FirstName), CHAR_LENGTH(FirstName), OCTET_LENGTH(FirstName) from Person
This is very much similar to LENGTH and CHAR_LENGTH functions. The difference comes when there are multibyte characters involved.
SELECT '€' as multibyte_char, LENGTH('€'), CHAR_LENGTH('€'), OCTET_LENGTH('€')
This happens because Euro (€) sign occupies 3 bytes in memory.
11. LPAD(str, len, padstr) / RPAD(str, len, padstr)
Inserts sub-string from position 0 of the string padstr at the beginning and end of the string str until the resultant string is of len characters.
SELECT FirstName, LastName, LPAD(CONCAT_WS(' ', FirstName, LastName), CHAR_LENGTH(CONCAT_WS(' ', FirstName, LastName))+CHAR_LENGTH('Mr. '), 'Mr. ') as DisplayName from Person
12. LTRIM(str, chars) / RTRIM(str, chars) / TRIM(str, chars)
Returns the string str after trimming all occurrences of char(s) from left, right or both ends. If chars are not specified in the arguments, spaces are trimmed.
SELECT LTRIM(' abc ') as L1, RTRIM(' abc ') as R1, TRIM(' abc ') as T1, LTRIM('xxxyyabcxyz', 'xyz') as L2, RTRIM('xxxyyabcxyz', 'xyz') as R2, TRIM('xxxyyabcxyz', 'xyz') as T2
13. POSITION(substr in str) / STRPOS(str, substr)
Finds the position of the substring substr in the string str. Remember, the index starts from 1 in PostgreSQL. Returns 0, if no match found.
SELECT Address, POSITION('Avenue' in Address) from Person
14. QUOTE_IDENT(str) / QUOTE_LITERAL(str)
This query quotes and un-quotes the string str. Most special characters are doubled.
SELECT Address, QUOTE_IDENT(Address), QUOTE_LITERAL(Address) from Person
15. REPLACE(str, from_str, to_str)
Replaces all occurrences of sub-string from_str with sub-string to_str in the string str. It is case-sensitive.
SELECT Address, REPLACE(Address, 's', 'SS') from Person
Reverses the string str.
SELECT FirstName, REVERSE(FirstName) from Person
17. REGEXP_MATCHES(str, pattern)
Returns all substrings that match the POSIX Regex pattern.
SELECT Address, REGEXP_MATCHES(Address, '.[sN]i.') from Perso
18. REGEXP_REPLACE(str, pattern, newstr)
Replaces all substrings that match the POSIX Regex pattern with the newstr.
SELECT Address, REGEXP_MATCHES(Address, '..[e][n]..'), REGEXP_REPLACE(Address, '..[e][n]..', 'Street') from Person
19. REGEXP_SPLIT_TO_ARRAY(str, pattern)
Splits the string str into an array of substrings separated by POSIX Regex pattern. Pattern E’\\s+’ means one or more blank spaces.
SELECT Address, REGEXP_SPLIT_TO_ARRAY(Address, E'\\s+') from Person
20. REGEXP_SPLIT_TO_TABLE(str, pattern)
Splits the string str into a table of substrings separated by POSIX Regex pattern.
SELECT Address, REGEXP_SPLIT_TO_TABLE(Address, E'\\s+') from Person
21. SUBSTRING(str from pos for len)
Returns a substring from string str starting at position pos of length len.
SELECT FirstName, SUBSTRING(FirstName from 2 for 4) as a sub from Person
22. SUBSTRING(str from posix_pattern) / SUBSTRING(str from sql_pattern for escape)
Returns a substring from string str that matches the POSIX Regex or SQL Regex. Regex is a big, wonderful and extremely useful topic in computers. It is recommended to get hold of Regex patterns before implementing them haphazardly.
SELECT FirstName, SUBSTRING(FirstName from '...$') as sub1, substring(FirstName from '%#"o_a#"_%' for '#') as sub2 from Person
Conclusion – PostgreSQL String Functions
So, to conclude, these along with other built-in functions are what makes PostgreSQL so powerful. The inclusion of regex patterns adds more power to it. Once the art of writing Regex patterns is learned and mastered, playing with the database would be much more fun.
This has been a guide to PostgreSQL String Functions. Here we discussed how to use string functions in PostgreSQL programming with the help of examples. You can also go through our other suggested articles to learn more–