SQL ELT function
Returns the nth element of the string list that follows, counting from 1.
- Catégorie
- Strings
- Returns
string or NULL- In this category
- 92 of 172
Syntaxe
ELT(n, str1, str2, ...)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| 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 | Oui | Supported under this name. |
| SQLite | Not built in | Use a CASE expression. |
| Oracle | Not built in | Use a CASE expression or DECODE. |
Exemples
MySQL
SELECT ELT(2, 'small', 'medium', 'large') AS label; -- medium
MySQL
SELECT id, ELT(priority, 'low', 'normal', 'high') AS label FROM tasks;
Bon à savoir
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, MySQL.
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.