A Quick Overview of the array_shuffle() Function in PostgreSQL

In PostgreSQL array_shuffle() is a system function that randomly shuffles the first dimension of a given array.

The array_shuffle() function was introduced in PostgreSQL 16, which was released on September 14th 2023.

Syntax

The syntax goes like this:

array_shuffle ( anyarray )

So we must pass an array to the function whenever we use it. The array can be an array of any type (hence the anyarray part of the syntax).

Example

Here’s an example to demonstrate:

SELECT array_shuffle( ARRAY[1,2,3,4,5,6,7,8,9,10] );

Result:

     array_shuffle      
------------------------
{8,10,6,2,3,9,4,1,5,7}

In this example I passed an array that consists of numbers 1 to 10. The function shuffled those elements around and returned the result.

Let’s run it again:

SELECT array_shuffle( ARRAY[1,2,3,4,5,6,7,8,9,10] );

Result:

     array_shuffle      
------------------------
{7,3,5,10,4,1,2,6,8,9}

A different result, but still with the same array elements.

Multi-dimensional Arrays

If the array is a multi-dimensional array, array_shuffle() applies to the first dimension:

SELECT array_shuffle( ARRAY[ [1,2,3],[4,5,6],[7,8,9],[10,11,12] ] );

Result:

            array_shuffle             
--------------------------------------
{{10,11,12},{1,2,3},{7,8,9},{4,5,6}}

So here we can see that the arrays have been shuffled, but the elements within those arrays haven’t.

Wrong Data Type

An error is returned when the argument is not an array. The error may depend on the argument.

For example:

SELECT array_shuffle([ 'Cat', 'Dog', 'Bird', 'Fox' ] );

Result:

ERROR:  syntax error at or near "["
LINE 1: SELECT array_shuffle([ 'Cat', 'Dog', 'Bird', 'Fox' ] );
^

Here I omitted the ARRAY keyword for declaring the array.

Here’s another example that produces an error:

SELECT array_shuffle( 'Cat' );

Result:

ERROR:  could not determine polymorphic type because input has type unknown

And:

SELECT array_shuffle( "Cat" );

Result:

ERROR:  column "Cat" does not exist
LINE 1: SELECT array_shuffle( "Cat" );
^

And another:

SELECT array_shuffle( 1 );

Result:

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