Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the position of a value in PostgreSQL arrays

Tags:

How can I get the position of a value in PostgreSQL arrays? There's .index() method for Python and array_search() function for PHP, but I cannot find any such function for PostgreSQL. Should I write a stored function to do that? I prefer to solve by using a built-in function.

like image 369
minhee Avatar asked Jan 10 '12 03:01

minhee


People also ask

How do you find the number of positions in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

Which of the function gives you the position of the value in an array?

The INDEX function returns a value or the reference to a value from within a table or range. There are two ways to use the INDEX function: If you want to return the value of a specified cell or array of cells, see Array form.

What is [] in PostgreSQL?

We access array elements using the subscript within square brackets [] . By default, PostgreSQL uses one-based numbering for array elements.


1 Answers

The documentation recommends using the generate_subscripts function. The function below emulate's PHP's array_search:

CREATE FUNCTION array_search(needle ANYELEMENT, haystack ANYARRAY) RETURNS INT AS $$     SELECT i       FROM generate_subscripts($2, 1) AS i      WHERE $2[i] = $1   ORDER BY i $$ LANGUAGE sql STABLE; 

This returns the index of the first match, if present. If you want all matches, simply change RETURNS INT to RETURNS SETOF INT. This function, as is, returns NULL if no match is found.

This function only works with one-dimensional arrays.

Also, bear in mind that array_search(NULL, a) always returns NULL, even if the array contains null elements:

> SELECT array_search(null, array[1, 2, null, 4]);  array_search  --------------  (1 row) 

This is because SQL considers NULL = NULL to be unknown (i.e. NULL). See functions-comparison. If you want array_search to be able to find NULL elements, change

     WHERE $2[i] = $1 

to

     WHERE $2[i] IS NOT DISTINCT FROM $1 
like image 177
Joey Adams Avatar answered Oct 16 '22 14:10

Joey Adams