TExcelTAD
Home › PostgreSQL › PostgreSQL String Functions

PostgreSQL String Functions

PostgreSQL has a large toolbox for working with text: changing case, trimming, cutting, searching, replacing, splitting and formatting. This lesson tours the functions you will use most.

Case, length and concatenation

pgsql · try it yourself
SELECT upper('Postgres')         AS upper,
       lower('Postgres')         AS lower,
       initcap('the salt road')  AS initcap,
       length('Chloé')           AS length,
       'Tad' || 'Books'          AS concat_op,
       concat('Order #', 42, NULL, '!') AS concat_fn,
       concat_ws(', ', 'Leeds', NULL, 'UK') AS concat_ws;
  upper   |  lower   |    initcap    | length | concat_op | concat_fn  | concat_ws
----------+----------+---------------+--------+-----------+------------+-----------
 POSTGRES | postgres | The Salt Road |      5 | TadBooks  | Order #42! | Leeds, UK
(1 row)

The || operator returns NULL if any part is NULL; concat and concat_ws (concat with separator) simply skip NULLs.

Trimming and padding

pgsql · try it yourself
SELECT '[' || trim('   spaced   ') || ']'      AS trim,
       '[' || ltrim('   left') || ']'          AS ltrim,
       '[' || rtrim('right   ') || ']'         AS rtrim,
       trim(BOTH '-' FROM '--code--')          AS custom_trim,
       lpad('42', 6, '0')                      AS lpad,
       rpad('ab', 5, '.')                      AS rpad;
   trim   | ltrim  |  rtrim  | custom_trim |  lpad  | rpad
----------+--------+---------+-------------+--------+-------
 [spaced] | [left] | [right] | code        | 000042 | ab...
(1 row)

Extracting parts

Function Example Result
left(s, n), right(s, n) left('Postgres', 4) Post
substring(s from i for n) / substr(s, i, n) substr('Postgres', 5, 3) gre
split_part(s, sep, n) split_part('a@b.com', '@', 2) b.com
position(sub in s) / strpos(s, sub) strpos('Postgres', 'g') 5

The domain of each customer's email, and the initials of each author:

pgsql · try it yourself
SELECT email,
       split_part(email, '@', 1) AS user_part,
       split_part(email, '@', 2) AS domain,
       strpos(email, '@')        AS at_position
FROM customers
WHERE id IN (1, 2, 4);

SELECT name,
       left(name, 1) || left(split_part(name, ' ', 2), 1) AS initials
FROM authors
WHERE id <= 4;
         email          | user_part  |   domain    | at_position
------------------------+------------+-------------+-------------
 anna.k@example.com     | anna.k     | example.com |           7
 ben.carter@example.com | ben.carter | example.com |          11
 david.kim@example.com  | david.kim  | example.com |          10
(3 rows)

      name      | initials
----------------+----------
 Maria Okafor   | MO
 Lars Henriksen | LH
 Aiko Tanaka    | AT
 Daniel Reyes   | DR
(4 rows)

Replacing and translating

pgsql · try it yourself
SELECT replace('The Salt Road', 'Road', 'Path')  AS replace,
       translate('2024-05-15', '-', '/')          AS translate,
       overlay('ABCDEF' placing 'xx' from 3 for 2) AS overlay,
       reverse('stressed')                        AS reverse,
       repeat('ab', 3)                            AS repeat;
    replace    | translate  | overlay | reverse  | repeat
---------------+------------+---------+----------+--------
 The Salt Path | 2024/05/15 | ABxxEF  | desserts | ababab
(1 row)

Regular expressions

Function Use
s ~ pattern does it match?
regexp_replace(s, pattern, replacement, flags) replace matches ('g' = all)
regexp_substr(s, pattern) first matching substring
regexp_matches(s, pattern, 'g') all matches (a set of arrays)
regexp_split_to_table(s, pattern) split into rows

Build URL-friendly "slugs" from book titles: lower case, anything that isn't a letter or digit becomes a hyphen:

pgsql · try it yourself
SELECT title,
       trim(BOTH '-' FROM regexp_replace(lower(title), '[^a-z0-9]+', '-', 'g')) AS slug
FROM books
WHERE id IN (6, 8, 19);
           title           |           slug
---------------------------+---------------------------
 Murder at Low Tide        | murder-at-low-tide
 Learning SQL the Calm Way | learning-sql-the-calm-way
 A Short History of Tea    | a-short-history-of-tea
(3 rows)

Splitting a string into rows or an array:

pgsql · try it yourself
SELECT regexp_split_to_table('sql, postgres ,  indexes', '\s*,\s*') AS word;

SELECT string_to_array('red|green|blue', '|') AS colours;
   word
----------
 sql
 postgres
 indexes
(3 rows)

     colours
------------------
 {red,green,blue}
(1 row)

Formatting

format() works like printf: %s inserts a value as text, %I quotes an identifier and %L quotes a literal (useful for building dynamic SQL safely). to_char formats numbers and dates:

pgsql · try it yourself
SELECT format('%s by %s costs %s', b.title, a.name, b.price) AS sentence,
       to_char(b.price, 'FM990.00" EUR"')                    AS price_label,
       format('SELECT * FROM %I WHERE name = %L', 'Order Items', 'O''Brien') AS dynamic_sql
FROM books b JOIN authors a ON a.id = b.author_id
WHERE b.id = 4;
                   sentence                   | price_label |                     dynamic_sql
----------------------------------------------+-------------+-----------------------------------------------------
 The Last Orbit by Lars Henriksen costs 16.75 | 16.75 EUR   | SELECT * FROM "Order Items" WHERE name = 'O''Brien'
(1 row)

Tip: String functions count characters, not bytes, so length('Chloé') is 5. Use octet_length if you need the byte size.

Test yourself

What does concat('a', NULL, 'b') return?

  1. NULL
  2. 'ab'
  3. 'aNULLb'
  4. An error

What does split_part('ben@carter.dev', '@', 2) return?

  1. 'ben'
  2. 'carter.dev'
  3. '@'
  4. 2

Which function pads '7' to '007'?

  1. rpad('7', 3, '0')
  2. lpad('7', 3, '0')
  3. repeat('0', 2) || 7 only
  4. to_number('007')