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.

Kindfunction
Example LanguageSQL

📝 Syntax

substring(string text from pattern text) → text
substring(string text from start integer for count integer) → text

⚙️ Parameters

string textThe string to extract from. Type text.
pattern textA POSIX regular expression; if it contains parentheses only the first capture group is returned. Type text.
start integerStart position for positional extraction, counted from 1. Type integer.
count integerHow 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏