Sub topic 6
Extracting parts with substring, left and right
This chapter covers the PostgreSQL functions that cut a piece out of a string by position, by count from either end, or by pattern. It assumes you know basic SELECT and WHERE syntax, how NULL behaves in expressions, and how to run queries in psql or another client. Earlier chapters covered the string types, NULL handling, concatenation and length. This chapter relies on the difference between characters and bytes.
The three tools at a glance
PostgreSQL gives you three families of extraction functions:
substringcuts by position and length, or by pattern.leftandrighttake a number of characters from the start or the end.substris a plain-function alias of the positional form ofsubstring.
All positions are 1-based, so the first character is at position 1. All positions count characters, not bytes, when the argument is text or varchar. In a UTF8 database, substring('héllo' FROM 2 FOR 1) returns é, not half of a two-byte sequence.
Positional substring
The SQL-standard syntax uses FROM and FOR. The function-call form takes the same arguments in the same order.
SELECT substring('PostgreSQL' FROM 1 FOR 8) AS standard_form,
substring('PostgreSQL', 1, 8) AS function_form,
substr('PostgreSQL', 1, 8) AS substr_form,
substring('PostgreSQL' FROM 5) AS to_the_end;The first three columns return PostgreS. The last returns greSQL, because leaving out FOR takes everything from the start position to the end.
A fixed-format code is a typical use case. Here a SKU has the layout CATEGORY-NUMBER-COLOR:
SELECT sku,
left(sku, 4) AS category,
substring(sku FROM 6 FOR 5) AS item_number,
right(sku, 3) AS color
FROM (VALUES ('ELEC-00421-BLK'), ('HOME-00007-WHT')) AS t(sku);The first row returns ELEC, 00421 and BLK.
Edge cases for positions
substring does not raise an error for most out-of-range positions. It treats the string as if it sat on an infinite number line and returns whatever part of your requested range overlaps the real characters.
| Call | Result | Why |
|---|---|---|
| `substring('PostgreSQL' FROM 0 FOR 3)` | `Po` | Positions 0, 1, 2 were requested. Position 0 does not exist, so only 2 characters come back. |
| `substring('PostgreSQL' FROM -2 FOR 5)` | `Po` | Positions -2 to 2 were requested. Only 1 and 2 exist. |
| `substring('PostgreSQL' FROM 20)` | empty string | The start is past the end. |
| `substring('PostgreSQL' FROM 3 FOR 100)` | `stgreSQL` | The count is clamped to the end of the string. |
| `substring('PostgreSQL' FROM 3 FOR -1)` | error | A negative length is rejected: `negative substring length not allowed`. |
| `substring(NULL::text FROM 1 FOR 2)` | `NULL` | The function is strict. A `NULL` input gives `NULL`. |
The FROM 0 FOR 3 case surprises many people. The length is measured from the requested start, not from the first real character. If you compute the start position, a result of 0 or less shortens the output without any warning.
A missing piece comes back as an empty string, not NULL. If you need to tell "nothing there" from "unknown", test explicitly with NULLIF(substring(...), '').
left and right
left(str, n) returns the first n characters. right(str, n) returns the last n. They are easier to read than the equivalent substring call, and they handle short strings without any arithmetic.
SELECT left('PostgreSQL', 4) AS first_four,
right('PostgreSQL', 3) AS last_three,
left('abc', 10) AS short_string,
left('PostgreSQL', -3) AS drop_last_three,
right('PostgreSQL', -4) AS drop_first_four;This returns Post, SQL, abc, Postgre and greSQL.
A negative n means "everything except n characters from the other end". left(str, -n) drops the last n characters, and right(str, -n) drops the first n. This replaces the common pattern substring(str FROM 1 FOR length(str) - n), which breaks when the string is shorter than n because the negative length raises an error.
Extracting by pattern
substring also accepts a regular expression. It returns the first match, or the text captured by the first parenthesized group if the pattern has one. It returns NULL when nothing matches.
SELECT substring('order #1234 shipped' FROM '#(\d+)') AS with_group,
substring('order #1234 shipped' FROM '\d+') AS no_group,
substring('order shipped' FROM '#(\d+)') AS no_match,
substring('a=1, b=2' FROM '(\w)=(\d)') AS first_group_only;The results are 1234, 1234, NULL and a. The last case shows that only the first group is returned. If you need several groups at once, use regexp_match, which returns an array. Regular expressions are covered in a later chapter.
The regular expression form is POSIX, and it is the same engine used by the ~ operator. Two details matter in practice:
- The match is not anchored. Add
^or$when you need the pattern to cover the start or the end of the string. - With the default
standard_conforming_strings = on, a backslash in a normal quoted string is literal, so'\d+'works as written.
A third pattern form exists, using SQL regular expressions with SIMILAR TO semantics. You mark the part to return with the escape character followed by a double quote:
SELECT substring('foobar' SIMILAR '%#"o_b#"%' ESCAPE '#') AS similar_form;This returns oob. It is rarely used in new code, because POSIX patterns are more widely known and more powerful.
Overload ambiguity
The two-argument call substring(text, text) is the regex form, and substring(text, integer) is the positional form. Untyped literals can make this ambiguous. If you pass a string that is meant to be a number, cast it so that PostgreSQL picks the form you intend:
SELECT substring('abc123', 4) AS positional,
substring('abc123', '\d+') AS pattern,
substring('abc123', '4'::int) AS cast_to_positional;The first and third columns return 123, and the second returns 123 by pattern. Casting is also the right fix when a parameter arrives as text from an application.
Worked example: splitting an email address
A common task is to get the domain from an email. A naive version uses position:
SELECT email,
substring(email FROM position('@' IN email) + 1) AS domain_naive,
substring(email FROM '@(.*)$') AS domain_regex
FROM (VALUES ('[email protected]'), ('not-an-email')) AS t(email);For [email protected] both columns return example.com. For not-an-email the two differ. position returns 0 when the character is missing, so the naive form starts at position 1 and returns the whole string not-an-email. The regex form returns NULL, which correctly signals that there is no domain.
This is the main reason to prefer the pattern form when a delimiter may be missing. If you must use positions, guard the call:
SELECT CASE WHEN position('@' IN email) > 0
THEN substring(email FROM position('@' IN email) + 1)
END AS domain_guarded
FROM (VALUES ('[email protected]'), ('not-an-email')) AS t(email);Characters, bytes and bytea
For text and varchar, every function here works in characters, so multibyte text is safe. The same function names applied to bytea values work in bytes. The result of substring on a bytea column can therefore cut through a multibyte character if you later convert it to text. If you store text, keep it in a text type.
Performance note
substring, left and right on a column in the WHERE clause prevent the planner from using an ordinary index on that column, because the index stores the whole value. For a prefix test, col LIKE 'ELEC%' can use a suitable B-tree index, but left(col, 4) = 'ELEC' cannot. Alternatively, create an expression index on left(col, 4) and use the exact same expression in the query. Indexing is covered in the last chapter.
Exercise
A column phone holds values like '(415) 555-0199'. Write an expression that returns only the area code '415', first by position and then by pattern. Which version is safer if some rows lack the parentheses?
Show answer
By position: substring(phone FROM 2 FOR 3). By pattern: substring(phone FROM '\((\d{3})\)'). The pattern version is safer, because it returns NULL for rows without parentheses. The positional version would return whatever characters sit at positions 2 to 4, giving wrong data without any error.
Exercise
What do left('database', -3), right('database', -3) and substring('database' FROM 0 FOR 3) return?
Show answer
left('database', -3) returns 'datab', because it drops the last 3 characters. right('database', -3) returns 'abase', because it drops the first 3. substring('database' FROM 0 FOR 3) returns 'da', because the requested range covers positions 0, 1 and 2 and position 0 does not exist.