MySQL POSITION() Function
MySQL POSITION() Function
The POSITION() function finds the 1-based character position of the first occurrence of a substring inside a string. It uses standard ANSI SQL IN syntax instead of comma-separated arguments.
Syntax
POSITION(substr IN str)
- substr: The substring to find.
- str: The source string to search inside.
- Return value:
1-based position of the first match,0if missing, orNULLif either input isNULL.
In MySQL, POSITION(substr IN str) is an exact synonym for the two-argument form LOCATE(substr, str).
Practical Example
Suppose you inspect shipping addresses in demo_orders to locate the apartment marker '#' before splitting suite numbers.
SELECT
order_id,
shipping_address,
POSITION('#' IN shipping_address) AS suite_marker_pos
FROM demo_orders
ORDER BY order_id;
| order_id | shipping_address | suite_marker_pos |
|---|---|---|
| 301 | 742 Oak St #4B | 12 |
| 302 | 19 Pine Ave | 0 |
| 303 | #100 Main Rd | 1 |
| 304 | NULL | NULL |
Row 303 returns 1 because '#' appears at the very first character, while row 302 returns 0 because no '#' is present.
Common Mistakes & NULL Behavior
- Using a comma instead of IN: Writing
POSITION('#', shipping_address)throws a SQL syntax error. You must writePOSITION(substr IN str)with theINkeyword. - Trying to add a starting offset: Unlike
LOCATE(substr, str, pos),POSITION()has no syntax for a starting offset. Switch toLOCATE()when you need to skip earlier matches. - Reversing substr and str: Putting the column before
IN(POSITION(shipping_address IN '#')) swaps haystack and needle and returns0. - NULL handling: Either
NULLinput makesPOSITION()returnNULL; an emptysubstr('') returns1.
Frequently Asked Questions
When should I choose POSITION() over LOCATE() or INSTR()?
Use POSITION(substr IN str) when you want ANSI SQL portability across PostgreSQL and MySQL. Use LOCATE() when you need a starting offset pos.
Is POSITION() case-sensitive?
It respects the column collation. Default _ci collations match case-insensitively unless you cast with BINARY.
What does POSITION('' IN 'abc') return?
It returns 1, because an empty string matches immediately at the start of any non-NULL string.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.