Fix “function array_sample(integer, integer) does not exist” in PostgreSQL

If you’re getting an error that reads “function array_sample(integer, integer) does not exist” when using the array_sample() function in PostgreSQL, it’s probably because your first argument is not an array. In particular, this specific error message implies that the first argument is an integer.

The first argument for this function must be an array.

To fix this error, be sure that your first argument to array_sample() is an array, not an integer.

Example of Error

Here’s an example of code that produces the error:

SELECT array_sample( 1, 2 );

Result:

ERROR:  function array_sample(integer, integer) does not exist
LINE 1: SELECT array_sample( 1, 2 );
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

Here I passed an integer as the first argument to array_sample() but it doesn’t accept an integer as the first argument. The second argument can (and must) be an integer, but the first argument must be an array of any type.

Solution

We can fix the problem by ensuring that the first argument is an array.

Example:

SELECT array_sample( ARRAY[ 'Cat', 'Dog', 'Bird', 'Fox' ], 2 );

Result:

 array_sample 
--------------
{Dog,Fox}

This time the function worked without error.