Lesson

MySQL FIND_IN_SET() Function

10 min reading
Free Course

MySQL FIND_IN_SET() Function

The FIND_IN_SET() function locates a string inside a comma-separated list of values and returns its 1-based position. It helps query legacy denormalized columns that store tags or roles as CSV text.

Syntax

FIND_IN_SET(str, strlist)
  • str: The single value to search for (must not contain a comma).
  • strlist: A string made of comma-separated items, such as 'new,sale,featured'.
  • Return value: 1-based position if found, 0 if missing, or NULL if either argument is NULL.

Unlike LIKE '%sale%', which falsely matches 'wholesale', FIND_IN_SET() compares whole comma-delimited tokens.

Practical Example

Suppose demo_products stores promotional labels in a tags column. You want to find every product tagged 'sale' and check where 'sale' sits in each list.

SELECT
    product_id,
    product_name,
    tags,
    FIND_IN_SET('sale', tags) AS sale_pos
FROM demo_products
WHERE FIND_IN_SET('sale', tags) > 0;
product_id product_name tags sale_pos
10 Wireless Mouse new,sale,featured 2
14 Laptop Stand sale 1
19 Desk Lamp clearance,sale 2

Any product tagged 'wholesale' without 'sale' evaluates to 0 and is excluded by the WHERE filter.

Common Mistakes & NULL Behavior

  • Spaces after commas break matches: FIND_IN_SET('sale', 'new, sale') returns 0 because the second item is ' sale', not 'sale'. Remove spaces with REPLACE(tags, ', ', ',') if data is inconsistent.
  • Commas inside the search term: If str contains a comma, FIND_IN_SET() cannot match it properly and returns 0.
  • NULL propagation and empty lists: FIND_IN_SET(NULL, 'a,b') and FIND_IN_SET('a', NULL) both return NULL. Searching an empty list '' returns 0.
  • Full table scans: WHERE FIND_IN_SET(...) > 0 cannot use a standard B-tree index. For large tables, normalize tags into a join table instead.

Frequently Asked Questions

Why does FIND_IN_SET() return 0 when the word is clearly in the string?

Check for spaces around commas. 'a, b' has a leading space on ' b', so FIND_IN_SET('b', 'a, b') returns 0.

Does FIND_IN_SET() work on MySQL SET columns?

Yes. MySQL stores SET values as compact bitmasks and exposes them as comma-separated strings, which FIND_IN_SET() searches directly.

Is FIND_IN_SET() case-sensitive?

It follows the collation of its arguments. With default _ci collations, 'SALE' matches 'sale'. Use a _bin collation for strict case matching.

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