简体   繁体   中英

What is alternative of ELT() function in Postgresql?

In MySQL, you can use the ELT() function to return an item from a specified position in a list.

How to find same in Postgresql

--- IN MYSQL

SELECT ELT(3, 'Cat', 'Dog', 'Horse') AS 'Result';

--- Result ----------

 Horse  

Use an array:

select (array['Cat', 'Dog', 'Horse'])[3];

If you need a function for compatibility reasons:

create or replace function elt(int, variadic text[])
returns text language sql immutable as $$
    select $2[$1]
$$;

select elt(3, 'Cat', 'Dog', 'Horse') AS "Result";

Live demo in db<>fiddle.

You might have to use a CASE expression in Postgres. Replace:

ELT(col, 'Cat', 'Dog', 'Horse')

with:

SELECT
    CASE col WHEN 1 THEN 'Cat'
             WHEN 2 THEN 'Dog'
             WHEN 3 THEN 'Horse' END AS animal
FROM yourTable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM