// strings reference

SQL FIELD function

Returns the index of the first argument within the remaining arguments, which lets you sort rows in a chosen order.

Category
Strings
Returns
integer
In this category
91 of 172

Syntax

FIELD(str, str1, str2, ...)
ORDER BY FIELD(column, 'b', 'a', 'c')

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Not built in No FIELD; use CASE WHEN col = 'b' THEN 1 ... END in ORDER BY.
PostgreSQL Different name or syntax array_position(ARRAY['b', 'a', 'c'], col) does the same job.
MySQL Yes Supported under this name.
SQLite Not built in No FIELD; use a CASE expression.
Oracle Not built in No FIELD; use DECODE or a CASE expression in ORDER BY.

Examples

MySQL

SELECT FIELD('b', 'a', 'b', 'c') AS idx;  -- 2

MySQL

SELECT id, status FROM tickets
ORDER BY FIELD(status, 'open', 'pending', 'closed');

Good to know

  • FIELD returns 0 when nothing matches, so in ascending order values missing from the list sort ahead of every listed value.
  • A NULL first argument also returns 0, not NULL, because NULL equals nothing in the list. COALESCE around FIELD therefore never fires.
  • Comparisons follow the collation, so with MySQL's case-insensitive default FIELD('A', 'a') is 1.

Questions about FIELD

How do I sort rows in a custom order in MySQL?

ORDER BY FIELD(status, 'open', 'pending', 'closed'). Values outside the list get 0 and sort first; to push them to the end, sort by FIELD(status, ...) = 0 first, then by FIELD(status, ...).

What does FIELD return when nothing matches?

Zero, including when the searched value is NULL. FIELD never returns NULL, so test for 0 rather than wrapping it in COALESCE.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, MySQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.