PostgreSQL Arrays
Any PostgreSQL type can be stored as an array: text[], integer[], even date[]. Arrays are handy for small lists that belong to one row, such as tags, phone numbers or a list of choices. In the sample data, books.tags is a text[] column.
SELECT title, tags FROM books WHERE id <= 5; title | tags
--------------------+-----------------
The Salt Road | {travel,family}
Harbor Lights | {family,sea}
Signal from Kepler | {space,aliens}
The Last Orbit | {space}
Clockwork Garden | {robots,nature}
(5 rows)
Writing array values
There are two ways to write an array: the ARRAY[…] constructor, or a string literal in curly braces:
SELECT ARRAY['sql', 'postgres'] AS constructor,
'{sql,postgres}'::text[] AS literal,
ARRAY[1, 2, 3] || 4 AS appended,
ARRAY[1, 2] || ARRAY[3, 4] AS concatenated,
array_length(ARRAY[10, 20, 30], 1) AS length; constructor | literal | appended | concatenated | length
----------------+----------------+-----------+--------------+--------
{sql,postgres} | {sql,postgres} | {1,2,3,4} | {1,2,3,4} | 3
(1 row)
Accessing elements
Array positions start at 1, not 0. Slices use [from:to]. Asking for a position that doesn't exist returns NULL rather than an error:
SELECT title,
tags[1] AS first_tag,
tags[2] AS second_tag,
tags[3] AS third_tag,
tags[1:2] AS first_two,
cardinality(tags) AS how_many
FROM books
WHERE id IN (8, 10, 4); title | first_tag | second_tag | third_tag | first_two | how_many
---------------------------+-----------+------------+-----------+-----------------+----------
The Last Orbit | space | | | {space} | 1
Learning SQL the Calm Way | sql | databases | beginner | {sql,databases} | 3
Rust for Curious Minds | rust | systems | beginner | {rust,systems} | 3
(3 rows)
Searching arrays
| Expression | True when |
|---|---|
'space' = ANY (tags) |
the array contains the value |
tags @> ARRAY['sql', 'databases'] |
the array contains all these values |
tags && ARRAY['sql', 'rust'] |
the arrays overlap (share at least one value) |
tags <@ ARRAY[…] |
every element is in the other array |
SELECT title FROM books WHERE 'space' = ANY (tags);
SELECT title FROM books WHERE tags @> ARRAY['sql', 'databases'];
SELECT title FROM books WHERE tags && ARRAY['rust', 'algorithms']; title
--------------------
Signal from Kepler
The Last Orbit
Moon Socks
(3 rows)
title
---------------------------
Learning SQL the Calm Way
Postgres in Practice
(2 rows)
title
------------------------
Rust for Curious Minds
Algorithms on a Napkin
(2 rows)
The @>, <@ and && operators can use a GIN index (CREATE INDEX ON books USING gin (tags)).
Modifying arrays
UPDATE books SET tags = array_append(tags, 'bestseller') WHERE id = 13;
UPDATE books SET tags = array_remove(tags, 'sea') WHERE id = 6;
UPDATE books SET tags[1] = 'crime' WHERE id = 7;
SELECT id, tags FROM books WHERE id IN (6, 7, 13) ORDER BY id;UPDATE 1
UPDATE 1
UPDATE 1
id | tags
----+-------------------------------
6 | {detective}
7 | {crime,courtroom}
13 | {dragons,counting,bestseller}
(3 rows)
array_prepend, array_cat, array_replace and array_position complete the toolbox.
Arrays to rows and back
unnest expands an array into one row per element; array_agg collects rows into an array. Together they let you analyse tags like normal data. The most common tags in the shop:
SELECT tag, count(*) AS books
FROM books, unnest(tags) AS tag
GROUP BY tag
HAVING count(*) > 1
ORDER BY books DESC, tag; tag | books
-----------+-------
family | 4
beginner | 3
detective | 3
space | 3
databases | 2
sea | 2
sql | 2
(7 rows)
unnest … WITH ORDINALITY adds the position, and array_agg rebuilds arrays:
SELECT t.tag, t.pos
FROM books, unnest(tags) WITH ORDINALITY AS t (tag, pos)
WHERE id = 8;
SELECT category_id, array_agg(DISTINCT tag ORDER BY tag) AS all_tags
FROM books, unnest(tags) AS tag
WHERE category_id IN (2, 4)
GROUP BY category_id; tag | pos
-----------+-----
sql | 1
databases | 2
beginner | 3
(3 rows)
category_id | all_tags
-------------+-------------------------------------------------------------
2 | {aliens,nature,robots,space}
4 | {algorithms,beginner,databases,postgresql,rust,sql,systems}
(2 rows)
Arrays or a separate table?
| Use an array when … | Use a separate table when … |
|---|---|
| the list is small and belongs to one row | items have their own attributes (who added a tag, when) |
| you mostly read it as a whole | you need foreign keys (tags must exist in a tag list) |
| order matters and is simple | you join and filter by the items a lot |
Note: Tags in real applications often start as an array and later move to a
book_tags (book_id, tag_id)table. Both designs are valid; choose the simpler one that meets your needs.
Test yourself
What does (ARRAY['a', 'b', 'c'])[1] return?
- 'a'
- 'b'
- NULL
- An error
Which condition is true if tags contains at least one of 'sql' or 'rust'?
- tags @> ARRAY['sql','rust']
- tags && ARRAY['sql','rust']
- tags = ARRAY['sql','rust']
- tags <@ ARRAY['sql','rust']
Which function turns an array into a set of rows?
- array_agg
- unnest
- string_to_array
- cardinality