Knowledge base / SQL

SQL POSITION: substring location, prefixes and missing matches

I distinguish substring presence from a prefix, correct position counting and show extraction after a confirmed separator.

Kajo RudzińskiPublished Updated 4 min read

A magnifying lens locates the first distinctive piece in a sequence.

POSITION locates the first occurrence of a substring. I separate three tasks: checking presence, checking the beginning and extracting part of a string. Each can use a position, but the condition must match the actual task.

The main examples use PostgreSQL 18 with ordinary text. For the case-sensitivity example I explicitly select the C collation. Other engines have separately identified equivalents. All strings and identifiers are synthetic.

Count positions from one

PostgreSQL documents POSITION and STRPOS as locating the first occurrence, returning 0 when the fragment is absent.

SELECT POSITION('SQL' IN 'Learn SQL') AS found_at;

The result is 7. Learn occupies positions 1 through 5, the space is at 6 and S is at 7. Zero-based indexing from another programming language does not apply here.

SELECT POSITION('Laptop' IN 'Nowoczesny Laptop z procesorem i7') AS found_at;

The result is 12. The Polish word Nowoczesny has ten characters, followed by a space at 11 and L at 12. Writing out the characters exposes the off-by-one error without needing to claim that a query was executed.

Distinguish absence from missing input

In test@example.com, the @ character starts at position 5. It is absent from example.com, giving 0. Finding the character is not complete email validation: a string might contain several @ characters or otherwise have an invalid structure.

SELECT POSITION('@' IN 'test@example.com') AS found_at;
SELECT POSITION('@' IN 'example.com') AS absent;

For missing input, I preserve the distinction between unknown text and known text without the fragment. I do not automatically replace every missing result with 0. In a filter such as POSITION('@' IN email) > 0, a null record does not satisfy the condition. A quality report that needs missing emails should identify them separately with email IS NULL.

A substring in the middle is not a prefix

The synthetic string 600148222 contains 48 but does not begin with it. A condition greater than zero looks anywhere in the input. Here the position is 5 because four characters precede 48.

SELECT POSITION('48' IN '600148222') AS anywhere;
SELECT POSITION('48' IN '481234567') AS at_start;

The outputs are 5 and 1. Assuming contacts has a text phone column, the prefix condition is:

SELECT contact_id, phone
FROM contacts
WHERE POSITION('48' IN phone) = 1
ORDER BY contact_id;

This remains a text rule. It does not validate a telephone number. A plus sign, spaces or a different notation require an agreed normalisation policy first. I avoid stripping arbitrary characters simply to make a match appear.

One sequence starts with the highlighted pair while another contains the same pair in the middle.

Evaluate case behaviour in the engine’s context

Case sensitivity is not a single rule for all SQL engines. In PostgreSQL I can explicitly apply the C collation to a simple ASCII example:

SELECT POSITION('sql' IN ('Learn SQL' COLLATE "C")) AS found_at;

This gives 0 because lowercase sql differs from SQL. If a simple task needs case-insensitive matching, I can explicitly transform both sides according to an agreed rule. That does not establish a complete normalisation policy for every writing system.

In MySQL, POSITION is a synonym for two-argument LOCATE. The LOCATE documentation explains comparison behaviour and the version accepting a starting position. I inspect collation and argument types instead of assuming the controlled PostgreSQL result applies. SQL Server CHARINDEX likewise compares according to its input collation.

Check argument order when changing engines

Engine Find c in abcde Result
PostgreSQL 18 POSITION('c' IN 'abcde') 3
PostgreSQL 18 strpos('abcde', 'c') 3
MySQL 8.4 LOCATE('c', 'abcde') 3
SQL Server CHARINDEX('c', 'abcde') 3
SQLite instr('abcde', 'c') 3

When porting a query, I consult CHARINDEX and SQLite instr. STRPOS and instr take the input string first; LOCATE and CHARINDEX take the search fragment first. Renaming the function mechanically can reverse the intended question.

Find the separator before extracting the suffix

Assume items contains a code field. I want everything after the first hyphen. In PostgreSQL I can combine POSITION, SUBSTRING and CASE:

SELECT code,
       CASE WHEN POSITION('-' IN code) > 0
            THEN SUBSTRING(code FROM POSITION('-' IN code) + 1)
            ELSE NULL
       END AS suffix
FROM items
ORDER BY code;

AB-12 produces 12. AB-12-X produces 12-X because the rule uses the first separator. AB12 has no separator and gives null through the explicit ELSE branch. I avoid accidentally returning the whole input by adding one to an absent position of 0.

This pattern is not a universal way to extract a surname from a person’s full name. Names can contain several components, and the first space does not establish their meaning. The extraction rule is appropriate only when the separator belongs to an agreed input format.

Exercise: write expectations for each boundary

List four inputs: a fragment at the beginning, a fragment in the middle, an absent fragment and missing input. Identify the expected position and whether each satisfies greater than zero or equal to one. Then add a second separator to the extraction example.

Explaining those differences prepares you to use positions inside a larger transformation. For substring substitution, continue with REPLACE.

Key takeaways

Where does POSITION start counting?

At 1. Zero means that the fragment is absent from known text; it does not indicate the first character.

Does POSITION greater than zero check a prefix?

No. It checks for presence anywhere. For the start of the text, use position equal to 1 after establishing the input format.

Does this SQL Server example use POSITION?

The SQL Server equivalent shown here is CHARINDEX. Porting a query also requires checking argument order and collation behaviour.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.