MySQL FIND_IN_SET() Function
The FIND_IN_SET() function in MySQL helps you locate a specific string within a comma-separated list of strings. It's particularly useful when you need to check if a value exists within a set of values stored as a single string.
FIND_IN_SET(): Definition and Usage
This function is a convenient way to search within string lists. It returns the position of the search string within the list, or 0 if the string isn't found. Keep in mind that NULL values in either the search string or the list will result in a NULL return value.
Syntax
Syntax
FIND_IN_SET(string, string_list)
Parameter Values
| Parameter | Description |
|---|---|
string |
The string you're searching for. This is required. |
string_list |
A comma-separated list of strings to search within. This is required. |
Return Values
The function returns:
- The position of the string in the list (a number greater than 0) if found.
0if the string is not found in the list.NULLif either the string or the string list isNULL.
Examples
Searching for a String in a List
This example searches for "q" within the list "s,q,l".
Syntax
SELECT FIND_IN_SET("q", "s,q,l");
Output
2
Searching for a Non-Existent String
Searching for "a" (which is not in the list).
Syntax
SELECT FIND_IN_SET("a", "s,q,l");
Output
0
Handling a NULL List
Demonstrating the behavior when the string list is NULL.
Syntax
SELECT FIND_IN_SET("q", NULL);
Output
NULL