substring(string from pattern) — Extract a substring with a SQL regular expression
Last updated: 2026-11-04
substring(string from pattern) — Extract a substring with a SQL regular expression
substring(string from pattern) extracts a piece of a string using PostgreSQL's POSIX regular expression engine, which makes it the most convenient tool for parsing semi-structured text. If the pattern contains parentheses only the first capture group is returned; when nothing matches the result is NULL rather than an empty string.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
substring(string text from pattern text) → text
substring(string text from start integer for count integer) → text
⚙️ Parameters
| string text | The string to extract from. Type text. |
|---|---|
| pattern text | A POSIX regular expression; if it contains parentheses only the first capture group is returned. Type text. |
| start integer | Start position for positional extraction, counted from 1. Type integer. |
| count integer | How many characters to take for positional extraction. Type integer. |
Returns:text — the extracted substring. Returns NULL when the pattern does not match.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | code | year_part | prefix | first_three
----+---------------+-----------+--------+-------------
1 | ORD-2024-0815 | 2024 | ORD | ORD
2 | SKU-99-BLUE | | SKU | SKU
3 | ABC123 | | | ABC
4 | no-code | | | no-
(4 rows)
📌 Key Points
- When the pattern has parentheses only the first capture group comes back; use regexp_match() with array unnesting to get them all.
- A non-match yields NULL — wrap the call in coalesce() if you need an empty string instead.
- PostgreSQL uses POSIX advanced regular expressions, so [0-9] style classes, the \d, \w and \s shorthands and [[:digit:]] bracket expressions all work.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhen should I use the two forms of substring()?
AAn integer after from is positional (from 2 for 3 takes characters 2 through 4); a regular expression after from is for pulling meaningful fields out of a fixed format, such as the year from a ticket code.