position(substring in string) — Locate the first occurrence of a substring

Last updated: 2026-11-04

position(substring in string) — Locate the first occurrence of a substring

position() returns the 1-based index of the first occurrence of a substring, and is a common building block for "does it contain" checks, prefix extraction and slicing text before a delimiter. It returns 0 rather than NULL when the substring is absent, so compare against 0 instead of testing for NULL.

Kindfunction
Example LanguageSQL

📝 Syntax

position(substring text in string text) → integer
strpos(string text, substring text) → integer

⚙️ Parameters

substring textThe substring to look for. Type text.
string textThe string being searched. Type text.

Returns:integer — the 1-based index of the first occurrence, or 0 when it is not found. Returns NULL if either argument is NULL.

▶ 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 | path                     | pos | pos_alt
----+--------------------------+-----+---------
  1 | /var/lib/postgresql/data |  10 |      10
  2 | /var/lib/mysql/data      |   0 |       0
  3 | /srv/app                 |   0 |       0
(3 rows)

📌 Key Points

More case studies coming soon.

📚 Related Reference

❓ FAQ

QWhat is the difference between position() returning 0 and returning NULL?
A0 means "searched, not found", while NULL means "the needle itself was NULL, so nothing was searched". Test containment with > 0, never with IS NOT NULL.
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%

🙏 帮我们做得更好

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

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