Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - IN Operator get Position

Tags:

sql

postgresql

Is it possible to get the position (index) of first argument of a list of arguments with a operator as IN?

The result I'm looking for is something as next:

SELECT 2 IN(2, 3, 1); -- Result I want is 0 but with IN is true
SELECT 3 IN(2, 3, 1); -- Result I want is 1 but with IN is true
SELECT 0 IN(2, 3, 1); -- Result I want is -1 but with IN is false
SELECT 1 IN(1, 1, 3); -- RESULT I WANT IS 0 ,1 but with IN is true
like image 663
Pau Avatar asked Sep 17 '26 11:09

Pau


2 Answers

You can't do this with a "plain" IN clause, but you can do this with an array and the unnest function:

select t.idx
from unnest(array[2,3,1]) with ordinality t(v,idx)
where t.v = 2;

select t.idx
from unnest(array[1, 1, 3]) with ordinality t(v,idx)
where t.v = 1;

However, if the value to search for is not in the array, you will get no rows at all.

in postgres can useful function POSITION, return first index in string example:

select position('2' in '2,3,1,2') // return 1
like image 40
Piotr Rogowski Avatar answered Sep 19 '26 23:09

Piotr Rogowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!