Talk:Array Index

From PostgreSQL wiki

Jump to: navigation, search

Current idx snippet return nothing if second argument is missing in array, whereas intarray idx returns 0 [1]. Something like this should work as contrib intarray version:

CREATE OR REPLACE FUNCTION idx(anyarray, anyelement)
 RETURNS int AS 
$$
 SELECT COALESCE( (SELECT i FROM (
    SELECT generate_series(array_lower($1,1),array_upper($1,1))
 ) g(i)
 WHERE $1[i] = $2
 LIMIT 1), 0);
$$ LANGUAGE sql IMMUTABLE;
Personal tools