9.19. Функции и операторы для работы с массивами

В Таблице 9.51 показаны имеющиеся специальные операторы для типов-массивов. Кроме них для массивов определены обычные операторы сравнения, показанные в Таблице 9.1. Эти операторы сравнения сопоставляют содержимое массивов по элементам, используя при этом функцию сравнения для B-дерева, определённую для типа данного элемента по умолчанию, и упорядочивают их по первому различию. В многомерных массивах элементы просматриваются по строкам (индекс последней размерности меняется в первую очередь). Если содержимое двух массивов совпадает, а размерности отличаются, результат их сравнения будет определяться первым отличием в размерностях. (В PostgreSQL до версии 8.2 поведение было другим: два массива с одинаковым содержимым считались одинаковыми, даже если число их размерностей и границы индексов различались.)

Таблица 9.51. Операторы для работы с массивами

Оператор

Описание

Пример(ы)

anyarray @> anyarrayboolean

Первый массив содержит второй (имеется ли для каждого элемента второго массива равный ему в первом)? (Повторяющиеся элементы рассматриваются на общих основаниях, поэтому массивы ARRAY[1] и ARRAY[1,1] считаются содержащими друг друга.)

ARRAY[1,4,3] @> ARRAY[3,1,3]t

anyarray <@ anyarrayboolean

Первый массив содержится во втором?

ARRAY[2,2,7] <@ ARRAY[1,7,4,2,6]t

anyarray && anyarrayboolean

Массивы пересекаются (у них есть общие элементы)?

ARRAY[1,4,3] && ARRAY[2,1]t

anyarray || anyarrayanyarray

Соединяет два массива. Если один из операндов — NULL или пустой массив, оператор никак не действует; в противном случае число размерностей массивов должно быть одинаковым (этот случай показан в первом примере) или могут отличаться на один (это иллюстрирует второй пример).

ARRAY[1,2,3] || ARRAY[4,5,6,7]{1,2,3,4,5,6,7}

ARRAY[1,2,3] || ARRAY[[4,5,6], [7,8,9]]{{1,2,3},{4,5,6},{7,8,9}}

anyelement || anyarrayanyarray

Вставляет элемент в начало массива (массив должен быть пустым или одномерным).

3 || ARRAY[4,5,6]{3,4,5,6}

anyarray || anyelementanyarray

Вставляет элемент в конец массива (массив должен быть пустым или одномерным).

ARRAY[4,5,6] || 7{4,5,6,7}


Подробнее поведение операторов с массивами описано в Разделе 8.15. За дополнительными сведениями об операторах, поддерживающих индексы, обратитесь к Разделу 11.2.

В Таблице 9.52 перечислены функции, предназначенные для работы с массивами. Дополнительная информация о них и примеры использования приведены в Разделе 8.15.

Таблица 9.52. Функции для работы с массивами

Функция

Описание

Пример(ы)

array_append ( anyarray, anyelement ) → anyarray

Добавляет элемент в конец массива (так же, как оператор anyarray || anyelement).

array_append(ARRAY[1,2], 3){1,2,3}

array_cat ( anyarray, anyarray ) → anyarray

Соединяет два массива (так же, как оператор anyarray || anyarray).

array_cat(ARRAY[1,2,3], ARRAY[4,5]){1,2,3,4,5}

array_dims ( anyarray ) → text

Возвращает текстовое представление размерностей массива.

array_dims(ARRAY[[1,2,3], [4,5,6]])[1:2][1:3]

array_fill ( anyelement, integer[] [, integer[]] ) → anyarray

Возвращает массив, заполненный заданным значением и имеющий размерности, указанные во втором аргументе. В необязательном третьем аргументе могут быть заданы нижние границы для каждой размерности (по умолчанию 1).

array_fill(11, ARRAY[2,3]){{11,11,11},{11,11,11}}

array_fill(7, ARRAY[3], ARRAY[2])[2:4]={7,7,7}

array_length ( anyarray, integer ) → integer

Возвращает длину указанной размерности массива. (Для пустых или несуществующих размерностей массива выдаёт не 0, а NULL.)

array_length(array[1,2,3], 1)3

array_length(array[]::int[], 1)NULL

array_length(array['text'], 2)NULL

array_lower ( anyarray, integer ) → integer

Возвращает нижнюю границу указанной размерности массива.

array_lower('[0:2]={1,2,3}'::integer[], 1)0

array_ndims ( anyarray ) → integer

Возвращает число размерностей массива.

array_ndims(ARRAY[[1,2,3], [4,5,6]])2

array_position ( anyarray, anyelement [, integer] ) → integer

Возвращает позицию первого вхождения второго аргумента в массиве либо NULL в случае отсутствия соответствующего элемента. Если задан третий аргумент, поиск начинается с заданной позиции. Массив должен быть одномерным. Эта функция определяет равенство как IS NOT DISTINCT FROM, что позволяет искать и значения NULL.

array_position(ARRAY['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], 'mon')2

array_positions ( anyarray, anyelement ) → integer[]

Возвращает массив позиций всех вхождений второго аргумента в одномерном массиве, заданном первым аргументом. Эта функция определяет равенство как IS NOT DISTINCT FROM, что позволяет искать и значения NULL. Результат NULL возвращается, только если в качестве массива передаётся NULL; в случае же отсутствия искомого значения в заданном массиве возвращается пустой массив.

array_positions(ARRAY['A','A','B','A'], 'A'){1,2,4}

array_prepend ( anyelement, anyarray ) → anyarray

Вставляет элемент в начало массива (так же, как оператор anyelement || anyarray).

array_prepend(1, ARRAY[2,3]){1,2,3}

array_remove ( anyarray, anyelement ) → anyarray

Удаляет из массива все элементы, равные заданному значению. Массив должен быть одномерным. Эта функция определяет равенство как IS NOT DISTINCT FROM, что позволяет удалять и элементы NULL.

array_remove(ARRAY[1,2,3,2], 2){1,3}

array_replace ( anyarray, anyelement, anyelement ) → anyarray

Заменяет каждый элемент массива, равный второму аргументу, значением третьего аргумента.

array_replace(ARRAY[1,2,5,4], 5, 3){1,2,3,4}

array_to_string ( array anyarray, delimiter text [, null_string text] ) → text

Представляет все элементы массива в виде текстовых строк и объединяет эти строки через разделитель, заданный параметром delimiter. Если в параметре null_string передана отличная от NULL строка, эта строка будет представлять содержащиеся в массиве элементы NULL, в противном случае такие элементы опускаются.

array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')1,2,3,*,5

array_upper ( anyarray, integer ) → integer

Возвращает верхнюю границу указанной размерности массива.

array_upper(ARRAY[1,8,3,7], 1)4

cardinality ( anyarray ) → integer

Возвращает общее число элементов в массиве (0, если массив пуст).

cardinality(ARRAY[[1,2],[3,4]])4

string_to_array ( string text, delimiter text [, null_string text] ) → text[]

Разделяет заданную параметром string строку на поля по разделителю delimiter и формирует из полученных подстрок массив значений text. Если в качестве delimiter передаётся NULL, каждый символ string становится отдельным элементом массива. Если в delimiter передаётся пустая строка, вся строка string воспринимается как одно поле и помещается в один элемент массива. Если в аргументе null_string передана отличная от NULL строка, поля, совпадающие с этой строкой, заменяются значениями NULL.

string_to_array('xx~~yy~~zz', '~~', 'yy'){xx,NULL,zz}

unnest ( anyarray ) → setof anyelement

Разворачивает массив в набор строк. Элементы массива прочитываются в порядке хранения.

unnest(ARRAY[1,2])

 1
 2

unnest(ARRAY[['foo','bar'],['baz','quux']])

 foo
 bar
 baz
 quux

unnest ( anyarray, anyarray [, ... ] ) → setof anyelement, anyelement [, ... ]

Разворачивает массивы (возможно разных типов) в набор кортежей. Если массивы имеют разную длину, кортежи дополняются до большей длины значениями NULL. Эта форма допускается только в предложении FROM; см. Подраздел 7.2.1.4.

select * from unnest(ARRAY[1,2], ARRAY['foo','bar','baz']) as x(a,b)

 a |  b
---+-----
 1 | foo
 2 | bar
   | baz


Примечание

В поведении string_to_array по сравнению с PostgreSQL версий до 9.1 произошли два изменения. Во-первых, эта функция возвращает пустой массив (содержащий 0 элементов), а не NULL, когда входная строка имеет нулевую длину. Во-вторых, если в качестве разделителя задан NULL, эта функция разбивает строку по символам, а не просто возвращает NULL, как было раньше.

Вы также можете узнать об агрегатной функции, работающей с массивами, array_agg в Разделе 9.21.

9.19. Array Functions and Operators #

Table 9.54 shows the specialized operators available for array types. In addition to those, the usual comparison operators shown in Table 9.1 are available for arrays. The comparison operators compare the array contents element-by-element, using the default B-tree comparison function for the element data type, and sort based on the first difference. In multidimensional arrays the elements are visited in row-major order (last subscript varies most rapidly). If the contents of two arrays are equal but the dimensionality is different, the first difference in the dimensionality information determines the sort order.

Table 9.54. Array Operators

Operator

Description

Example(s)

anyarray @> anyarrayboolean

Does the first array contain the second, that is, does each element appearing in the second array equal some element of the first array? (Duplicates are not treated specially, thus ARRAY[1] and ARRAY[1,1] are each considered to contain the other.)

ARRAY[1,4,3] @> ARRAY[3,1,3]t

anyarray <@ anyarrayboolean

Is the first array contained by the second?

ARRAY[2,2,7] <@ ARRAY[1,7,4,2,6]t

anyarray && anyarrayboolean

Do the arrays overlap, that is, have any elements in common?

ARRAY[1,4,3] && ARRAY[2,1]t

anycompatiblearray || anycompatiblearrayanycompatiblearray

Concatenates the two arrays. Concatenating a null or empty array is a no-op; otherwise the arrays must have the same number of dimensions (as illustrated by the first example) or differ in number of dimensions by one (as illustrated by the second). If the arrays are not of identical element types, they will be coerced to a common type (see Section 10.5).

ARRAY[1,2,3] || ARRAY[4,5,6,7]{1,2,3,4,5,6,7}

ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9.9]]{{1,2,3},{4,5,6},{7,8,9.9}}

anycompatible || anycompatiblearrayanycompatiblearray

Concatenates an element onto the front of an array (which must be empty or one-dimensional).

3 || ARRAY[4,5,6]{3,4,5,6}

anycompatiblearray || anycompatibleanycompatiblearray

Concatenates an element onto the end of an array (which must be empty or one-dimensional).

ARRAY[4,5,6] || 7{4,5,6,7}


See Section 8.15 for more details about array operator behavior. See Section 11.2 for more details about which operators support indexed operations.

Table 9.55 shows the functions available for use with array types. See Section 8.15 for more information and examples of the use of these functions.

Table 9.55. Array Functions

Function

Description

Example(s)

array_append ( anycompatiblearray, anycompatible ) → anycompatiblearray

Appends an element to the end of an array (same as the anycompatiblearray || anycompatible operator).

array_append(ARRAY[1,2], 3){1,2,3}

array_cat ( anycompatiblearray, anycompatiblearray ) → anycompatiblearray

Concatenates two arrays (same as the anycompatiblearray || anycompatiblearray operator).

array_cat(ARRAY[1,2,3], ARRAY[4,5]){1,2,3,4,5}

array_dims ( anyarray ) → text

Returns a text representation of the array's dimensions.

array_dims(ARRAY[[1,2,3], [4,5,6]])[1:2][1:3]

array_fill ( anyelement, integer[] [, integer[] ] ) → anyarray

Returns an array filled with copies of the given value, having dimensions of the lengths specified by the second argument. The optional third argument supplies lower-bound values for each dimension (which default to all 1).

array_fill(11, ARRAY[2,3]){{11,11,11},{11,11,11}}

array_fill(7, ARRAY[3], ARRAY[2])[2:4]={7,7,7}

array_length ( anyarray, integer ) → integer

Returns the length of the requested array dimension. (Produces NULL instead of 0 for empty or missing array dimensions.)

array_length(array[1,2,3], 1)3

array_length(array[]::int[], 1)NULL

array_length(array['text'], 2)NULL

array_lower ( anyarray, integer ) → integer

Returns the lower bound of the requested array dimension.

array_lower('[0:2]={1,2,3}'::integer[], 1)0

array_ndims ( anyarray ) → integer

Returns the number of dimensions of the array.

array_ndims(ARRAY[[1,2,3], [4,5,6]])2

array_position ( anycompatiblearray, anycompatible [, integer ] ) → integer

Returns the subscript of the first occurrence of the second argument in the array, or NULL if it's not present. If the third argument is given, the search begins at that subscript. The array must be one-dimensional. Comparisons are done using IS NOT DISTINCT FROM semantics, so it is possible to search for NULL.

array_position(ARRAY['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], 'mon')2

array_positions ( anycompatiblearray, anycompatible ) → integer[]

Returns an array of the subscripts of all occurrences of the second argument in the array given as first argument. The array must be one-dimensional. Comparisons are done using IS NOT DISTINCT FROM semantics, so it is possible to search for NULL. NULL is returned only if the array is NULL; if the value is not found in the array, an empty array is returned.

array_positions(ARRAY['A','A','B','A'], 'A'){1,2,4}

array_prepend ( anycompatible, anycompatiblearray ) → anycompatiblearray

Prepends an element to the beginning of an array (same as the anycompatible || anycompatiblearray operator).

array_prepend(1, ARRAY[2,3]){1,2,3}

array_remove ( anycompatiblearray, anycompatible ) → anycompatiblearray

Removes all elements equal to the given value from the array. The array must be one-dimensional. Comparisons are done using IS NOT DISTINCT FROM semantics, so it is possible to remove NULLs.

array_remove(ARRAY[1,2,3,2], 2){1,3}

array_replace ( anycompatiblearray, anycompatible, anycompatible ) → anycompatiblearray

Replaces each array element equal to the second argument with the third argument.

array_replace(ARRAY[1,2,5,4], 5, 3){1,2,3,4}

array_sample ( array anyarray, n integer ) → anyarray

Returns an array of n items randomly selected from array. n may not exceed the length of array's first dimension. If array is multi-dimensional, an item is a slice having a given first subscript.

array_sample(ARRAY[1,2,3,4,5,6], 3){2,6,1}

array_sample(ARRAY[[1,2],[3,4],[5,6]], 2){{5,6},{1,2}}

array_shuffle ( anyarray ) → anyarray

Randomly shuffles the first dimension of the array.

array_shuffle(ARRAY[[1,2],[3,4],[5,6]]){{5,6},{1,2},{3,4}}

array_to_string ( array anyarray, delimiter text [, null_string text ] ) → text

Converts each array element to its text representation, and concatenates those separated by the delimiter string. If null_string is given and is not NULL, then NULL array entries are represented by that string; otherwise, they are omitted. See also string_to_array.

array_to_string(ARRAY[1, 2, 3, NULL, 5], ',', '*')1,2,3,*,5

array_upper ( anyarray, integer ) → integer

Returns the upper bound of the requested array dimension.

array_upper(ARRAY[1,8,3,7], 1)4

cardinality ( anyarray ) → integer

Returns the total number of elements in the array, or 0 if the array is empty.

cardinality(ARRAY[[1,2],[3,4]])4

trim_array ( array anyarray, n integer ) → anyarray

Trims an array by removing the last n elements. If the array is multidimensional, only the first dimension is trimmed.

trim_array(ARRAY[1,2,3,4,5,6], 2){1,2,3,4}

unnest ( anyarray ) → setof anyelement

Expands an array into a set of rows. The array's elements are read out in storage order.

unnest(ARRAY[1,2])

 1
 2

unnest(ARRAY[['foo','bar'],['baz','quux']])

 foo
 bar
 baz
 quux

unnest ( anyarray, anyarray [, ... ] ) → setof anyelement, anyelement [, ... ]

Expands multiple arrays (possibly of different data types) into a set of rows. If the arrays are not all the same length then the shorter ones are padded with NULLs. This form is only allowed in a query's FROM clause; see Section 7.2.1.4.

select * from unnest(ARRAY[1,2], ARRAY['foo','bar','baz']) as x(a,b)

 a |  b
---+-----
 1 | foo
 2 | bar
   | baz


See also Section 9.21 about the aggregate function array_agg for use with arrays.