trim_array()

A function for removing elements from the end of an array
This entry relates to a PostgreSQL feature which is part of PostgreSQL 14, due to be released in late 2021.

trim_array() is a system function for removing elements from the end of an array.

trim_array() was added in PostgreSQL 14.

Usage

trim_array ( array anyarray, n integer ) → anyarray

trim_array() is an SQL:2008 standard function implementing array slice functionality, specifically removing the last n elements from an array and returning the result.

If the array is multidimensional, trimming operates on dimensions rather than elements of a dimension.

Change history

Examples

Basic usage of trim_array():

postgres=# SELECT trim_array(ARRAY['a', 'b', 'c'], 2);
 trim_array 
------------
 {a}
(1 row)

postgres=# SELECT trim_array(ARRAY[1, 2, 3], 1);
 trim_array 
------------
 {1,2}
(1 row)

postgres=# SELECT trim_array(ARRAY[1, 2, 3], 0);
 trim_array 
------------
 {1,2,3}
(1 row)

Trimming multi-dimensional arrays:

postgres=# SELECT trim_array(ARRAY[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ], 1);
    trim_array     
-------------------
 {{1,2,3},{4,5,6}}
(1 row)

postgres=# SELECT trim_array(ARRAY[ [ [1, 2, 3] ], [ [4, 5, 6] ], [ [7, 8, 9] ] ], 1);
      trim_array       
-----------------------
 {{{1,2,3}},{{4,5,6}}}
(1 row)

Specifying an invalid number of elements:

postgres=# SELECT trim_array(ARRAY['a','b','c'], -2);
ERROR:  number of elements to trim must be between 0 and 3

Categories

System function