Working with ARRAYs

Functions for Manipulating Data in PostgreSQL

Brian Piccolo

Sr. Director, Digital Strategy

Before we get started

CREATE TABLE example

CREATE TABLE my_first_table (
    first_column text,
    second_column integer
);

INSERT example

INSERT INTO my_first_table 
    (first_column, second_column) VALUES ('text value', 12);
Functions for Manipulating Data in PostgreSQL

ARRAY a special type

Let's create a simple table with two array columns.

CREATE TABLE grades (
    student_id int,
    email text[][],
    test_scores int[]
);
Functions for Manipulating Data in PostgreSQL

INSERT statements with ARRAYS

Example INSERT statement:

INSERT INTO grades 
    VALUES (1, 
    '{{"work","[email protected]"},{"other","[email protected]"}}', 
    '{92,85,96,88}' );
Functions for Manipulating Data in PostgreSQL

Accessing ARRAYs

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          |
+--------+--------------------+-------------+

Note that PostgreSQL array indexes start with one and not zero.

Functions for Manipulating Data in PostgreSQL

Searching ARRAYs

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          |
+--------+--------------------+-------------+
Functions for Manipulating Data in PostgreSQL

ARRAY functions and operators

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          |
+---------+---------------------+-------------+
Functions for Manipulating Data in PostgreSQL

ARRAY functions and operators

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          |
+---------+---------------------+-------------+
Functions for Manipulating Data in PostgreSQL

Let's practice!

Functions for Manipulating Data in PostgreSQL

Preparing Video For Download...