StringsSQL standard

POSITION

Finds the character where a substring starts within a string.

Syntax

POSITION(<substring> IN <text>)
STRPOS(<text>, <substring>)

Returns the number of the character where the substring first starts, counting from 1. If there's no such substring — 0. Often used together with SUBSTRING or LEFT to cut out a piece before or after a certain character.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Where the @ is
SELECT POSITION('@' IN 'emma@example.com') AS at_sign,
POSITION('#' IN 'emma@example.com') AS not_found;
at_signnot_found
50
The first space in a phone number
SELECT name, phone,
POSITION(' ' IN phone) AS first_space
FROM employees;
namephonefirst_space
Emma+44 7700 9001234
LiamNULLNULL
Olivia+44 7700 9004564
Noah+44 7700 9007894
SophiaNULLNULL
Everything before the @
SELECT LEFT('emma@example.com', POSITION('@' IN 'emma@example.com') - 1) AS login;
login
emma

@ is the fifth character, so we take 4 characters from the left. For this task there's also the shorter SPLIT_PART.

Watch out

Not found means 0, not NULL. Check POSITION(…) > 0.

Case matters: POSITION('E' IN 'emma') gives 0. To ignore case, bring both sides to the same case with LOWER.

STRPOS takes its arguments in a different order: the text first, then what to look for — STRPOS('emma@example.com', '@').

Related functions

Learn more in the course