Sub topic 7
Finding Text with `strpos` and `position`
Prerequisites and the basic model
This chapter assumes you can write SELECT and WHERE queries and understand NULL. PostgreSQL provides two closely related functions for locating one string inside another:
strpos(string, substring)position(substring IN string)
Both return the position of the first matching occurrence. Positions start at 1, not 0. If the substring does not occur, both return 0.
SELECT strpos('PostgreSQL', 'SQL') AS strpos_result,
position('SQL' IN 'PostgreSQL') AS position_result,
strpos('PostgreSQL', 'Python') AS missing_result;The result is 7, 7, and 0. The SQL substring begins at the seventh character.
Choosing between the two forms
strpos uses an ordinary function-call style. position follows SQL syntax and reads more like a sentence. They have the same basic behavior.
| Expression | Meaning | Result |
|---|---|---|
| `strpos('abcabc', 'bc')` | Find `bc` in `abcabc` | 2 |
| `position('bc' IN 'abcabc')` | Find `bc` in `abcabc` | 2 |
| `strpos('abc', 'x')` | Find missing `x` | 0 |
Use whichever style fits your team’s conventions. position can be useful when writing portable SQL. strpos is often easier to compose with other PostgreSQL functions.
Both functions are case-sensitive. Searching for sql does not find SQL.
SELECT strpos('PostgreSQL', 'sql') AS lowercase_search,
strpos('PostgreSQL', 'SQL') AS uppercase_search;The first result is 0 and the second is 7.
Using positions in filters
A position is useful when you need to test whether text contains a marker. Since a missing substring produces 0, test for a value greater than 0.
SELECT id, email
FROM customers
WHERE strpos(email, '@') > 0;This returns rows whose email contains an at sign somewhere after the beginning. It does not validate the complete email format. For validation rules, combine several checks or use a suitable pattern.
You can also calculate the location and use it in a larger expression. For example, this query returns everything before the first slash:
SELECT path,
left(path, strpos(path, '/') - 1) AS first_part
FROM files
WHERE strpos(path, '/') > 0;The WHERE clause matters. Without it, a path with no slash would produce a length of -1, which is invalid for this use.
`NULL`, empty strings, and repeated text
If either argument is NULL, the result is NULL, because PostgreSQL cannot locate text when one input is unknown. An empty substring is found at position 1.
The functions return the first occurrence only. To find later occurrences, search a substring of the original value after the first match, or use regular expressions for more advanced matching.
Exercise
What does position('cat' IN 'concatenate') return, and what does strpos('concatenate', 'dog') return?
Show answer
The first expression returns 4, because cat starts at the fourth character. The second returns 0 because dog is absent.