PostgreSQL- ARRAY_PREPEND Function

The array_prepend function is used to prepend an element to the beginning of an array. It takes two arguments: the element you want to prepend, and the array to which you want to prepend the element.

Below is the syntax of the array_prepend function:

array_prepend(element, array)

Where:

element is the element you want to prepend to the array.

array is the array to which you want to prepend the element.

Below is an example of usingthe array_prepend function:

SELECT array_prepend(0, '{1, 2, 3}') AS result_array;

The output would be:

result_array 
-------------- 
{0,1,2,3} 
(1 row)

In this example, the array_prepend function added the value 0 to the beginning of the input array.

Here is another example of using the array_prepend function. Consider a table named log with an array column log_entries and you want to add a new log entry to all rows:

UPDATE log 
SET log_entries = array_prepend('New entry', log_entries) 
WHERE some_condition;

This query will update the log_entries arrays in the log table, adding 'New entry' to the beginning of each array that meets the specified condition.

Similar Posts