Lesson

MySQL POSITION() Function

10 min reading
Free Course

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, 0 if missing, or NULL if either input is NULL.

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 write POSITION(substr IN str) with the IN keyword.
  • Trying to add a starting offset: Unlike LOCATE(substr, str, pos), POSITION() has no syntax for a starting offset. Switch to LOCATE() 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 returns 0.
  • NULL handling: Either NULL input makes POSITION() return NULL; an empty substr ('') returns 1.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum