EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL String Functions
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL String Functions

By Priya PedamkarPriya Pedamkar

PostgreSQL String Functions

Introduction to PostgreSQL String Functions

PostgreSQL is a potent object-relational database management system. It provides many 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 to leverage to solve the bigger problem.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,112 ratings)

To illustrate various PostgreSQL String functions, we first need to create a database. The following database will be referred to in all the examples:

PostgreSQL String functions Example

PostgreSQL String functions Example Output

Examples of String Functions in PostgreSQL

Here we will discuss how to use the string function in PostgreSQL.

1. ASCII(str)

Returns the ASCII value of the leftmost character of the string str.

SELECT FirstName, ASCII(FirstName) from Person

PostgreSQL String Functions 1

2. BIT_LENGTH(str)

Returns the length of the string str in bits.

SELECT FirstName, BIT_LENGTH(FirstName) from Person

PostgreSQL String Functions 2

3. CHAR_LENGTH(str) / CHARACTER_LENGTH(str)

Returns the length of the string str in characters.

SELECT FirstName, CHAR_LENGTH(FirstName) from Person

PostgreSQL String Functions 3

4. CONCAT(str1, str2, …., strn)

Returns a string formed by joining str1 to strn. NULL arguments are ignored.

SELECT FirstName, LastName, CONCAT(FirstName, LastName) as DisplayName from Person

PostgreSQL String Functions 4

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

PostgreSQL String Functions 5

6. INITCAP(str)

Capitalizes the string, i.e. each word’s first letter is upper-cased, and the rest are lower-cased. Non-alphanumeric separators determine words.

Select INITCAP('This is a PostgreSQL example.')

PostgreSQL String Functions 6

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

PostgreSQL String Functions 7

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

PostgreSQL String Functions 8

9. LENGTH(str) / LENGTH(str, encoding)

Returns the length of the string str in characters. This is unlike the operation of the 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

PostgreSQL String Functions 9

10. OCTET_LENGTH(str)

Calculates the length of the string str in bytes.

SELECT FirstName, LENGTH(FirstName), CHAR_LENGTH(FirstName), OCTET_LENGTH(FirstName) from Person

PostgreSQL String Functions 10

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('€')

PostgreSQL String Functions 10-1

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

PostgreSQL String Functions 11

12. LTRIM(str, chars) / RTRIM(str, chars) / TRIM(str, chars)

Returns the string str after trimming all char(s) occurrences 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

PostgreSQL String Functions 12

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

PostgreSQL String Functions 13

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

PostgreSQL String Functions 14

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

REPLACE Functions 15

16. REVERSE(str)

Reverses the string str.

SELECT FirstName, REVERSE(FirstName) from Person

REVERSE Functions 16

17. REGEXP_MATCHES(str, pattern)

Returns all substrings that match the POSIX Regex pattern.

SELECT Address, REGEXP_MATCHES(Address, '.[sN]i.') from Perso

REGEXP_MATCHES 17

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

REGEXP_REPLACE 18

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

REGEXP_SPLIT_TO_ARRAY 19

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

REGEXP_SPLIT_TO_TABLE 20

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

SUBSTRING Functions 21

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 beneficial 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

PostgreSQL String Functions 22

Conclusion

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.

Recommended Articles

This has been a guide to PostgreSQL String Functions. Here we discussed how to use string functions with the help of examples. You can also go through our other suggested articles to learn more–

  1. String Functions In Java With Examples
  2. How to Install PostgreSQL?
  3. PostgreSQL Interview Questions
  4. Regex Functions in Python (Example)
  5. Learn Different Versions of PostgreSQL
  6. Different PostgreSQL Architecture
  7. PostgreSQL Features
Popular Course in this category
SQL Training Program (7 Courses, 8+ Projects)
  7 Online Courses |  8 Hands-on Projects |  73+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more