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.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
position(substring text in string text) → integer
strpos(string text, substring text) → integer
⚙️ Parameters
| substring text | The substring to look for. Type text. |
|---|---|
| string text | The 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
- A missing substring gives 0, not NULL, so test containment with position(x in s) > 0.
- position() and strpos() are the same function with the arguments in the opposite order.
- Matching is case sensitive; use strpos(lower(s), lower(x)) for a case-insensitive lookup.
💡 Related Cases
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.