// strings reference

SQL ELT function

Returns the nth element of the string list that follows, counting from 1.

Категория
Strings
Returns
string or NULL
In this category
92 of 172

Синтаксис

ELT(n, str1, str2, ...)

Поддержка движка

ДвижокSupportЗаметки
SQL Server Different name or syntax CHOOSE(n, ...) is the same function under another name.
PostgreSQL Not built in Use a CASE expression or (ARRAY['a', 'b'])[n].
MySQL Да Supported under this name.
SQLite Not built in Use a CASE expression.
Oracle Not built in Use a CASE expression or DECODE.

Примеры

MySQL

SELECT ELT(2, 'small', 'medium', 'large') AS label;  -- medium

MySQL

SELECT id, ELT(priority, 'low', 'normal', 'high') AS label
FROM tasks;

Полезно знать

  • ELT is 1-based: ELT(1, 'a', 'b') is 'a'. An index of 0, a negative index or one past the last argument returns NULL, not an error.
  • It is the mirror of FIELD: FIELD('b', 'a', 'b', 'c') gives the index 2, ELT(2, 'a', 'b', 'c') gives the value 'b'.
  • Because a bad index quietly returns NULL, wrap with COALESCE when a default label matters.

Questions about ELT

Is ELT the same as CHOOSE in SQL Server?

Yes: both take a 1-based index and return that element, and both return NULL when the index is out of range.

What happens if the index is out of range?

You get NULL. ELT(0, 'a') and ELT(5, 'a') are both NULL, which suits mapping codes to labels when every code is known.

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: SQL Server, 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.