MySQL FIELD() Function
MySQL FIELD() Function
The FIELD() function searches a list of arguments for a target value and returns its 1-based position. Developers most often use it to enforce custom business sort orders inside ORDER BY.
Syntax
FIELD(str, str1, str2, str3, ...)
- str: The target value to look up.
- str1, str2, ...: Two or more values to search from left to right.
- Return value:
1-based index of the first match, or0if not found or ifstrisNULL.
Indexing starts at 1 for str1. When no argument matches str, FIELD() returns 0.
Practical Example
In demo_orders, alphabetical sorting places 'cancelled' before 'pending' and 'shipped'. You can use FIELD() to put active fulfillment stages first.
SELECT
order_id,
order_code,
status,
FIELD(status, 'pending', 'packed', 'shipped', 'cancelled') AS priority_rank
FROM demo_orders
ORDER BY priority_rank, order_id;
| order_id | order_code | status | priority_rank |
|---|---|---|---|
| 41 | ORD-901 | pending | 1 |
| 42 | ORD-902 | packed | 2 |
| 43 | ORD-903 | shipped | 3 |
| 44 | ORD-904 | cancelled | 4 |
| 45 | ORD-905 | NULL | 0 |
Notice row 45: when status is NULL, FIELD() returns 0. Because 0 sorts before 1, NULL rows jump to the top unless handled explicitly.
Common Mistakes & NULL Behavior
- FIELD(NULL, ...) returns 0, not NULL: Even if
NULLappears inside the search list,FIELD(NULL, 'a', NULL, 'b')returns0becauseNULLis never equal toNULL. - Unexpected top sorting for unknown values: Unlisted statuses and
NULLvalues return0, placing them first in ascendingORDER BY. Sort byFIELD(status, ...) = 0, FIELD(status, ...)to push unknowns to the bottom. - Mixed numeric and string types: If all arguments are strings, MySQL compares them as strings. Mixing numbers and strings forces numeric conversion, which can cause unexpected matches.
Frequently Asked Questions
What is the difference between FIELD() and FIND_IN_SET()?
FIELD() takes separate SQL arguments (FIELD(x, 'a', 'b')). FIND_IN_SET() searches inside a single comma-separated string (FIND_IN_SET(x, 'a,b')).
Is FIELD() case-sensitive?
Under default case-insensitive collations like utf8mb4_0900_ai_ci, FIELD('Pending', 'pending', 'shipped') returns 1. Use BINARY or a _bin collation for exact case matching.
How do I push unmatched rows to the end when sorting with FIELD()?
Order by FIELD(status, 'shipped', 'packed', 'pending') DESC in reverse, or use ORDER BY (FIELD(...) = 0), FIELD(...).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.