The FIELD() function in MySQL is used to determine the index position of a value within a specified list of values. It is useful for finding the position of an element in a list, and it performs a case-insensitive search.
Syntax
FIELD(value, val1, val2, val3, ...)
Parameters
| Parameter | Description |
|---|---|
| value | Required. The value to search for in the list. |
| val1, val2, ... | Required. The list of values to search through. |
Definition and Use
- Purpose: Returns the 1-based index position of the specified
valuewithin the provided list of values. - Behavior:
- Returns
0if the value is not found. - Returns
0if the value isNULL.
- Returns
- Case-Insensitive: The comparison is not case-sensitive, so
"q"and"Q"are treated the same.
Usage Examples
Example 1: Basic String Search
To find the index position of "q" in the string list:
SELECT FIELD("q", "s", "q", "l");
Output:
| FIELD("q", "s", "q", "l") |
|---|
| 2 |
Explanation: "q" is the second element in the list.
Example 2: Case-Insensitive Search
To find the index position of "Q" in a string list:
SELECT FIELD("Q", "s", "q", "l");
Output:
| FIELD("Q", "s", "q", "l") |
|---|
| 2 |
Explanation: The function is case-insensitive, so "Q" matches "q" at position 2.
Example 3: Numeric Search
To find the index position of 5 in a numeric list:
SELECT FIELD(5, 0, 1, 2, 3, 4, 5);
Output:
| FIELD(5, 0, 1, 2, 3, 4, 5) |
|---|
| 6 |
Explanation: 5 is the 6th element in the numeric list.
Example 4: Value Not Found
To search for a value that does not exist in the list:
SELECT FIELD("x", "a", "b", "c");
Output:
| FIELD("x", "a", "b", "c") |
|---|
| 0 |
Explanation: "x" is not in the list, so the function returns 0.
Technical Details
- Availability: Available from MySQL 4.0 onwards.
- Return Type: Returns an integer indicating the 1-based index position or
0if the value is not found.
Applications
- Sorting: Assign priority to specific values by determining their position in a predefined list.
- Validation: Check if a value exists within a set of expected values.
- Custom Ranking: Create dynamic rankings based on predefined lists.
Key Notes
- The index returned is 1-based, meaning the first item in the list is at position 1.
- If the value or the list contains
NULL, the function returns0. - The function works with both strings and numbers, making it versatile for different data types.
The FIELD() function is a simple yet powerful tool for finding the position of elements in lists, enabling efficient ranking and validation in MySQL queries.