Sub topic 2
PostgreSQL Arrays: Inspecting, Changing, and Filtering
This chapter assumes you can write SELECT, INSERT, UPDATE, and WHERE, create a table, and reason about NULL in SQL. You should also be able to run queries in psql.
The examples use this table:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}');Inspecting arrays: cardinality, array_length, array_position
cardinality returns the total number of elements. array_length(arr, 1) returns the length of the first dimension. array_position returns the 1-based index of the first matching element, or NULL when nothing matches.
SELECT title,
cardinality(tags) AS n,
array_length(tags, 1) AS len,
array_position(tags, 'postgres') AS pos
FROM posts;Adding, removing, and replacing elements
Use array_append to add an element and array_remove to delete every element equal to a value. Guard the update so it does not add duplicates.
UPDATE posts
SET tags = array_append(tags, 'tutorial')
WHERE id = 1
AND NOT tags @> ARRAY['tutorial'];
UPDATE posts
SET tags = array_remove(tags, 'sql')
WHERE id = 1;NULL elements and empty arrays
An empty array has length NULL under array_length, but 0 under cardinality. Comparisons with ANY are also tricky: 1 = ANY (ARRAY[2, NULL]) returns NULL, not false, so a WHERE clause drops that row.
Filtering rows: @>, <@, &&, ANY and ALL
@> tests whether the column contains every listed value. <@ tests whether the column is contained in the list. && tests whether the two arrays share at least one value. ANY checks for one matching element, and ALL checks that every element matches.
SELECT title FROM posts WHERE tags @> ARRAY['postgres'];
SELECT title FROM posts WHERE tags && ARRAY['gin', 'sql'];
SELECT title FROM posts WHERE 'gin' = ANY (tags);
SELECT title FROM posts WHERE 'gin' <> ALL (tags);Exercise
Which rows does SELECT title FROM posts WHERE 'gin' <> ALL (tags); return, and why?
Show answer
It returns rows where no element of tags equals 'gin'. The "Intro to arrays" row has no 'gin' tag, so it is returned. The "Indexing" row contains 'gin', so it is excluded.