Робота з ARRAY

Функції для обробки даних у PostgreSQL

Brian Piccolo

Sr. Director, Digital Strategy

Перш ніж почати

Приклад CREATE TABLE

CREATE TABLE my_first_table (
    first_column text,
    second_column integer
);

Приклад INSERT

INSERT INTO my_first_table 
    (first_column, second_column) VALUES ('text value', 12);
Функції для обробки даних у PostgreSQL

ARRAY — особливий тип

Створімо просту таблицю з двома стовпцями-масивами.

CREATE TABLE grades (
    student_id int,
    email text[][],
    test_scores int[]
);
Функції для обробки даних у PostgreSQL

INSERT із масивами ARRAY

Приклад оператора INSERT:

INSERT INTO grades 
    VALUES (1, 
    '{{"work","[email protected]"},{"other","[email protected]"}}', 
    '{92,85,96,88}' );
Функції для обробки даних у PostgreSQL

Доступ до ARRAY

SELECT
   email[1][1] AS type,
   email[1][2] AS address,
   test_scores[1],
FROM grades;
+--------+--------------------+-------------+
| type   |  address           | test_scores |
|--------|--------------------|-------------|
| work   | [email protected] | 92          |
| work   | [email protected] | 76          |
+--------+--------------------+-------------+

Зверніть увагу: індекси масивів у PostgreSQL починаються з одиниці, а не з нуля.

Функції для обробки даних у PostgreSQL

Пошук у ARRAY

SELECT
   email[1][1] as type,
   email[1][2] as address,
   test_scores[1]
FROM grades
WHERE email[1][1] = 'work';
+--------+--------------------+-------------+
| type   |  address           | test_scores |
|--------|--------------------|-------------|
| work   | [email protected] | 92          |
| work   | [email protected] | 76          |
+--------+--------------------+-------------+
Функції для обробки даних у PostgreSQL

Функції та оператори ARRAY

SELECT
   email[2][1] as type,
   email[2][2] as address,
   test_scores[1]
FROM grades
WHERE 'other' = ANY (email);
+---------+---------------------+-------------+
| type    |  address            | test_scores |
|---------|-----------------------------------|
| other   | [email protected] | 92          |
| null    | null                | 76          |
+---------+---------------------+-------------+
Функції для обробки даних у PostgreSQL

Функції та оператори ARRAY

SELECT
   email[2][1] as type,
   email[2][2] as address,
   test_scores[1]
FROM grades
WHERE email @> ARRAY['other'];
+---------+---------------------+-------------+
| type    |  address            | test_scores |
|---------|-----------------------------------|
| other   | [email protected] | 92          |
| null    | null                | 76          |
+---------+---------------------+-------------+
Функції для обробки даних у PostgreSQL

Давайте потренуємось!

Функції для обробки даних у PostgreSQL

Preparing Video For Download...