MySQL FIND_IN_SET() Function

The FIND_IN_SET() function in MySQL is used to locate the position of a string within a list of strings separated by commas. It is a straightforward and useful function for working with comma-separated values (CSV) stored as strings.


Syntax

FIND_IN_SET(string, string_list)

Parameters

Parameter Description
string Required. The string to search for.
string_list Required. The comma-separated list of strings to search within.

Definition and Use

  • Purpose: Returns the 1-based position of a string in a comma-separated list.
  • Behavior:
    • If the string is not found, the function returns 0.
    • If the string or string_list is NULL, the function returns NULL.
    • If the string_list is an empty string (""), the function returns 0.

Usage Examples

Example 1: String Found in List

To find the position of "q" in a list of strings:

SELECT FIND_IN_SET("q", "s,q,l") AS Position;

Output:

Position
2

Explanation: "q" is the second element in the comma-separated list.


Example 2: String Not Found in List

To search for "a" in a list where it doesn't exist:

SELECT FIND_IN_SET("a", "s,q,l") AS Position;

Output:

Position
0

Explanation: "a" is not in the list, so the function returns 0.


Example 3: String List is NULL

To search within a NULL list:

SELECT FIND_IN_SET("q", NULL) AS Position;

Output:

Position
NULL

Explanation: If the string_list is NULL, the function returns NULL.


Example 4: Empty String List

To search within an empty list:

SELECT FIND_IN_SET("q", "") AS Position;

Output:

Position
0

Explanation: If the string_list is an empty string, the function returns 0.


Technical Details

  • Availability: Available from MySQL 4.0 onwards.
  • Return Type: Returns an integer indicating the 1-based position of the string, or 0/NULL as per the cases described above.

Applications

  1. Filtering Data: Search for values within a comma-separated list stored in a single column.
  2. Validation: Check whether a value exists in a predefined list.
  3. Dynamic Positioning: Retrieve the position of specific items within a CSV-like string.

Key Notes

  • The function is case-sensitive. For case-insensitive comparisons, you might need additional handling (e.g., LOWER()).
  • The string_list must be a properly formatted comma-separated list without spaces.
  • If you're working with large datasets, consider normalizing data instead of using CSV strings for better performance.

The FIND_IN_SET() function is a handy tool for handling and querying comma-separated values in MySQL, offering simple and efficient searching within lists.


Was this article helpful?