Sub topic 7
Finding text with strpos and position
PostgreSQL has one basic way to ask where a piece of text sits inside another: strpos, with position as its standard-SQL spelling. This chapter covers what they return, how that interacts with NULL, case and multibyte characters, and how to combine them with substring and left to cut strings at a found location. It assumes you can already run queries in psql or another client, and that you know the text type, NULL, and the basic extraction functions from the previous chapter.
The two spellings
Both forms answer the same question: at which character does the first occurrence of a substring start?
SELECT strpos('PostgreSQL', 'SQL') AS with_strpos,
position('SQL' IN 'PostgreSQL') AS with_position;Both columns return 8. The two differ only in argument order and syntax.
| Form | Argument order | Style |
|---|---|---|
| `strpos(string, substring)` | haystack first | ordinary function call |
| `position(substring IN string)` | needle first | SQL-standard keyword syntax |
The functions behave identically. Pick one and use it consistently in a codebase. Many people prefer strpos because it reads like other functions, and because you can pass it as a plain function call in generated SQL.
What the result means
The result is a 1-based position, counted in characters. The first character is position 1, not 0. If the substring does not occur, the result is 0. That is why 0 is a safe "not found" signal: no real match can start at position 0.
SELECT strpos('PostgreSQL', 'P') AS first_char,
strpos('PostgreSQL', 'Q') AS found_in_middle,
strpos('PostgreSQL', 'xyz') AS not_found;This returns 1, 8, and 0. Note that strpos('PostgreSQL', 'Q') is 8 because the first Q follows PostgreS, which is seven characters.
Only the first occurrence is reported. If the text contains the substring several times, you get the position of the leftmost one.
Edge cases
Several inputs behave in ways that surprise people the first time.
- NULL. If either argument is NULL, the result is NULL. A
WHERE strpos(col, 'x') > 0filter therefore drops NULL rows, as any comparison with NULL does. - Empty substring.
strpos('abc', '')returns1. An empty string is considered to occur at the start of every string. If your search term can be empty (for example from a user form), guard for that. - Case. The search is case-sensitive.
strpos('PostgreSQL', 'sql')returns0. - No wildcards. The substring is matched literally.
%,_, and regex characters have no special meaning, so you do not need to escape them. This is a real advantage overLIKEwhen the search term comes from data.
For a case-insensitive search, lower-case both sides:
SELECT strpos(lower('PostgreSQL'), lower('sql')) AS ci_position;This returns 8. The position is still valid for the original string, because lower keeps the same number of characters in common cases. Be careful with unusual Unicode, where case conversion can in principle change length. For typical business text it is safe.
Characters, not bytes
Positions count characters. In a UTF8 database, a multibyte character such as é counts as one.
SELECT strpos('héllo', 'l') AS char_position,
strpos('héllo', 'l') = 3 AS is_third_char;The result is 3. This matches substring, left, and right, which also work in characters, so a position from strpos is directly usable as an argument to them. Only octet_length and byte-oriented functions work in bytes.
Cutting text at a found position
The most common use of strpos is to feed its result into substring or left. A typical task is splitting an email address at the @:
SELECT email,
left(email, strpos(email, '@') - 1) AS local_part,
substring(email FROM strpos(email, '@') + 1) AS domain
FROM (VALUES ('[email protected]'),
('[email protected]')) AS t(email);For [email protected], strpos returns 4. left(email, 3) gives ana, and substring(email FROM 5) gives example.com. The - 1 and + 1 skip the separator itself. If the separator is longer than one character, add length(separator) instead of 1.
The not-found trap
This query works only when every row contains an @. When strpos returns 0, the arithmetic gives silently wrong results:
substring(email FROM 0 + 1)issubstring(email FROM 1), which returns the entire string, not NULL.left(email, 0 - 1)isleft(email, -1), which returns everything except the last character, because a negative count inleftmeans "all but the last n".
Both outputs look plausible and no error is raised, so bad rows pass unnoticed. Convert the 0 to NULL with NULLIF, so that the whole expression becomes NULL when the separator is missing:
SELECT email,
left(email, NULLIF(strpos(email, '@'), 0) - 1) AS local_part,
substring(email FROM NULLIF(strpos(email, '@'), 0) + 1) AS domain
FROM (VALUES ('[email protected]'),
('[email protected]'),
('not-an-email')) AS t(email);The third row now returns NULL in both columns. NULL propagates through the addition and subtraction, and both left and substring return NULL when their numeric argument is NULL.
You can also be explicit with CASE:
SELECT email,
CASE WHEN strpos(email, '@') > 0
THEN substring(email FROM strpos(email, '@') + 1)
ELSE 'unknown'
END AS domain
FROM (VALUES ('[email protected]'), ('not-an-email')) AS t(email);This returns example.com and unknown. Use CASE when you want a default value instead of NULL.
Finding the second occurrence
Unlike instr in Oracle or charindex in SQL Server, PostgreSQL's strpos has no start-offset argument. To find a later occurrence, search in the remainder of the string and then add the skipped characters back.
WITH s AS (SELECT 'a/b/c/d' AS path, '/' AS sep)
SELECT path,
strpos(path, sep) AS first_pos,
strpos(substring(path FROM strpos(path, sep) + length(sep)), sep)
+ strpos(path, sep) + length(sep) - 1 AS second_pos
FROM s;The first slash is at 2. The remainder after it is b/c/d, where the slash is at 2, so the second slash in the original string is at 2 + 2 + 1 - 1 = 4. The query returns 2 and 4. If the inner strpos returns 0, the arithmetic produces a wrong number, so apply the NULLIF guard again in real code.
This gets awkward quickly. When you only need a particular piece of a delimited string, split_part (covered later in this tutorial) is simpler. When the rules are more complex, a regular expression is clearer.
Finding the last occurrence
To find the last occurrence, reverse both strings, find the first match, and convert the position back:
SELECT length(path) - strpos(reverse(path), '/') + 1 AS last_slash
FROM (VALUES ('a/b/c')) AS t(path);The reversed string is c/b/a, where / is at 2. The result is 5 - 2 + 1 = 4, which is the position of the last slash in a/b/c. This formula works for a one-character separator. For a longer separator, reverse the separator too and subtract length(separator) - 1 more.
Using strpos in WHERE and indexes
strpos(col, 'text') > 0 works as a "contains" test, but it behaves differently from the pattern operators in one important way for performance. A B-tree index on col cannot help, and neither can a trigram index, because the planner does not connect strpos to either one. The query scans every row.
If the column is large and the search is frequent, use col LIKE '%text%' with a trigram index instead, as covered in the indexing chapter. The trade-off is that LIKE treats % and _ as wildcards, so you must escape them when the search term comes from user input. Use strpos when the table is small, the search is occasional, or the literal behavior matters more than speed.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Treating positions as 0-based | Off-by-one errors in cuts | Remember the first character is 1 |
| Testing `IS NULL` for not found | Never true for non-NULL inputs | Compare with `= 0` or `> 0` |
| Using the result unguarded in `left` or `substring` | Wrong text, no error | `NULLIF(strpos(...), 0)` or `CASE` |
| Expecting case-insensitive matching | Returns 0 for different case | Apply `lower` to both arguments |
| Expecting a start offset argument | Syntax error, wrong argument types | Search `substring` of the remainder |
| Using byte counts from `octet_length` as positions | Wrong cut on multibyte text | Stay with character-based functions |
Exercise
A table has a column named code with values like 'EU-1042', 'US-77' and 'LEGACY'. Write an expression that returns the part after the first hyphen ('1042', '77'), and returns NULL for 'LEGACY' instead of the whole string.
Show answer
Use NULLIF to turn the not-found result 0 into NULL, so substring receives a NULL start position: SELECT code, substring(code FROM NULLIF(strpos(code, '-'), 0) + 1) AS suffix FROM (VALUES ('EU-1042'), ('US-77'), ('LEGACY')) AS t(code); For 'EU-1042', strpos returns 3, so substring starts at 4 and returns '1042'. For 'LEGACY', strpos returns 0, NULLIF makes it NULL, and the whole expression is NULL. Without NULLIF, substring would start at position 1 and return 'LEGACY'.
Exercise
What do strpos('abc', ''), strpos('abc', 'B') and strpos(NULL, 'a') return?
Show answer
They return 1, 0 and NULL. An empty substring matches at the start of any string, the search is case-sensitive so 'B' is not found in 'abc', and any NULL argument gives a NULL result.