9.19. Функции и операторы для работы с массивами #
В Таблице 9.54 показаны имеющиеся специальные операторы для типов-массивов. Кроме них для массивов определены обычные операторы сравнения, показанные в Таблице 9.1. Эти операторы сравнения сопоставляют содержимое массивов по элементам, используя при этом функцию сравнения для B-дерева, определённую для типа данного элемента по умолчанию, и упорядочивают их по первому различию. В многомерных массивах элементы просматриваются по строкам (индекс последней размерности меняется в первую очередь). Если содержимое двух массивов совпадает, а размерности отличаются, результат их сравнения будет определяться первым отличием в размерностях.
Таблица 9.54. Операторы для работы с массивами
Оператор Описание Пример(ы) |
---|
Первый массив содержит второй (имеется ли для каждого элемента второго массива равный ему в первом)? (Повторяющиеся элементы рассматриваются на общих основаниях, поэтому массивы
|
Первый массив содержится во втором?
|
Массивы пересекаются (у них есть общие элементы)?
|
Соединяет два массива. Если один из операндов — NULL или пустой массив, оператор никак не действует; в противном случае число размерностей массивов должно быть одинаковым (этот случай показан в первом примере) или могут отличаться на один (это иллюстрирует второй пример). Если это массивы не одинаковых типов элементов, они будут приведены к общему типу (см. Раздел 10.5).
|
Вставляет элемент в начало массива (массив должен быть пустым или одномерным).
|
Вставляет элемент в конец массива (массив должен быть пустым или одномерным).
|
Подробнее поведение операторов с массивами описано в Разделе 8.15. За дополнительными сведениями об операторах, поддерживающих индексы, обратитесь к Разделу 11.2.
В Таблице 9.55 перечислены функции, предназначенные для работы с массивами. Дополнительная информация о них и примеры использования приведены в Разделе 8.15.
Таблица 9.55. Функции для работы с массивами
Функция Описание Пример(ы) |
---|
Добавляет элемент в конец массива (так же, как оператор
|
Соединяет два массива (так же, как оператор
|
Возвращает текстовое представление размерностей массива.
|
Возвращает массив, заполненный заданным значением и имеющий размерности, указанные во втором аргументе. В необязательном третьем аргументе могут быть заданы нижние границы для каждой размерности (по умолчанию
|
Возвращает длину указанной размерности массива. (Для пустых или несуществующих размерностей массива выдаёт не 0, а NULL.)
|
Возвращает нижнюю границу указанной размерности массива.
|
Возвращает число размерностей массива.
|
Возвращает позицию первого вхождения второго аргумента в массиве либо
|
Возвращает массив позиций всех вхождений второго аргумента в одномерном массиве, заданном первым аргументом. Эта функция определяет равенство как
|
Вставляет элемент в начало массива (так же, как оператор
|
Удаляет из массива все элементы, равные заданному значению. Массив должен быть одномерным. Эта функция определяет равенство как
|
Заменяет каждый элемент массива, равный второму аргументу, значением третьего аргумента.
|
Возвращает массив из
|
Случайным образом перемешивает элементы первой размерности массива.
|
Представляет все элементы массива в виде текстовых строк и объединяет эти строки через разделитель, заданный параметром
|
Возвращает верхнюю границу указанной размерности массива.
|
Возвращает общее число элементов в массиве (0, если массив пуст).
|
Сокращает массив, удаляя последние
|
Разворачивает массив в набор строк. Элементы массива прочитываются в порядке хранения.
1 2
foo bar baz quux |
Разворачивает массивы (возможно разных типов) в набор кортежей. Если массивы имеют разную длину, кортежи дополняются до большей длины значениями
a | b ---+----- 1 | foo 2 | bar | baz |
Вы также можете узнать об агрегатной функции, работающей с массивами, 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) |
---|
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
|
Is the first array contained by the second?
|
Do the arrays overlap, that is, have any elements in common?
|
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).
|
Concatenates an element onto the front of an array (which must be empty or one-dimensional).
|
Concatenates an element onto the end of an array (which must be empty or one-dimensional).
|
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) |
---|
Appends an element to the end of an array (same as the
|
Concatenates two arrays (same as the
|
Returns a text representation of the array's dimensions.
|
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
|
Returns the length of the requested array dimension. (Produces NULL instead of 0 for empty or missing array dimensions.)
|
Returns the lower bound of the requested array dimension.
|
Returns the number of dimensions of the array.
|
Returns the subscript of the first occurrence of the second argument in the array, or
|
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
|
Prepends an element to the beginning of an array (same as the
|
Removes all elements equal to the given value from the array. The array must be one-dimensional. Comparisons are done using
|
Replaces each array element equal to the second argument with the third argument.
|
Returns an array of
|
Randomly shuffles the first dimension of the array.
|
Converts each array element to its text representation, and concatenates those separated by the
|
Returns the upper bound of the requested array dimension.
|
Returns the total number of elements in the array, or 0 if the array is empty.
|
Trims an array by removing the last
|
Expands an array into a set of rows. The array's elements are read out in storage order.
1 2
foo bar baz quux |
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
a | b ---+----- 1 | foo 2 | bar | baz |
See also Section 9.21 about the aggregate function array_agg
for use with arrays.