arrays
a list in a column. ANY, unnest, @>, and the day it should have been a table.
- address
- everything.types.arrays
- part
- part 6, types and values
- chapter
- chapter 8 of 11
- reading time
- 7 min
an array column holds a list of values of one type: text[], int[]. subscripts start at 1. = ANY asks "is it in the list", @> "does it contain all of these", && "any of these", and unnest turns the list back into rows. a GIN index makes the containment questions fast.
the day you need to rename an element everywhere, count by element, or point a foreign key at one, it should have been a table.
the picture
you know how a spreadsheet cell sometimes ends up holding "red, large, sale"? that's a list in a cell, and you can't sort, count or filter by one of them without splitting the text. an array is the database doing that properly: a real list, with types and operators.
think of a pill organiser: one box per row, with numbered compartments, starting at 1. you can ask whether a box has a given pill, and you can tip a box out onto the table to look at each pill separately (unnest). what you can't do is make two boxes share a pill.
a[1] is eco, a[2:3] is the slice {new,sale}, and a[0] isn't an error, it's NULL: there's nothing there.literals and subscripts
two ways to write one: the ARRAY[...] constructor, or a string in braces that gets cast. quotes inside the braces protect spaces and commas, and an unquoted NULL is a NULL element:
SELECT ARRAY['eco', 'new'] AS constructor,
'{eco,new}'::text[] AS literal,
'{"left handed", NULL, "NULL", ""}'::text[] AS tricky,
(ARRAY[10, 20, 30, 40])[2:3] AS slice;| constructortext[] | literaltext[] | trickytext[] | sliceint4[] |
|---|---|---|---|
| {eco,new} | {eco,new} | {"left handed",NULL,"NULL",""} | {20,30} |
"NULL" in quotes is the four-letter string; bare NULL is the missing value. and an empty array has no length at all, which catches people:
SELECT cardinality('{}'::int[]) AS cardinality, array_length('{}'::int[], 1) AS array_length;| cardinalityint4 | array_lengthint4 |
|---|---|
| 0 | null |
array_length returns NULL for an empty array (it has no first dimension to measure). cardinality says 0.
asking about elements
shop's products have a tags text[] column. four operators cover almost every question:
- 1SELECT id, name, tags FROM products WHERE 'steel' = ANY (tags) ORDER BY id LIMIT 6;
| idint4 | nametext | tags_text |
|---|---|---|
| 1 | chef's knife | {steel,sharp} |
| 6 | hose reel | {steel} |
= ANY: steel is one of the elements.
= ANY tests one value against the list, the other three compare two whole arrays as sets, so order and repeats don't matter.SELECT 3 = ANY (ARRAY[1, NULL]);SELECT 3 = ANY (ARRAY[1, NULL]) AS not_found, 1 = ANY (ARRAY[1, NULL]) AS found, 'x' = ANY ('{}'::text[]) AS empty_list;| not_foundbool | foundbool | empty_listbool |
|---|---|---|
| null | t | f |
unnest: back to rows
unnest takes an array and returns one row per element. used with LATERAL (or just a comma in FROM), it works row by row, and WITH ORDINALITY adds the position:
| id | tags |
|---|---|
| 1 | {steel,sharp} |
| 3 | {} |
| 5 | {wired,closed-back} |
| 7 | {wood,kids} |
| id | tag | pos |
|---|---|---|
| 1 | steel | 1 |
| 1 | sharp | 2 |
| 5 | wired | 1 |
| 5 | closed-back | 2 |
| 7 | wood | 1 |
| 7 | kids | 2 |
pos. product 3 has an empty array, so it makes no rows and disappears; LEFT JOIN LATERAL ... ON true would keep it.the reverse is array_agg, which collects rows into an array (with an ORDER BY inside, or the order is whatever the rows arrived in):
SELECT tag, count(*) AS products, array_agg(id ORDER BY id) FILTER (WHERE id < 30) AS some_ids
FROM products, unnest(tags) AS tag
GROUP BY tag
ORDER BY count(*) DESC, tag
LIMIT 4;| tagtext | productsint8 | some_idsint4[] |
|---|---|---|
| new | 68 | {16,17,22,23,24} |
| eco | 34 | {16,22} |
| sale | 33 | {10,20,27} |
| outdoor | 10 | {12,21,29} |
a GIN index on an array
a b-tree indexes a whole value, which is useless for "contains sale". a GIN index is an inverted index: one entry per element, each pointing at every row that has it. it serves @>, &&, <@ and =:
CREATE TABLE posts AS
SELECT i AS id, CASE WHEN i % 97 = 0 THEN ARRAY['rare', 'sql'] ELSE ARRAY['sql'] END AS tags
FROM generate_series(1, 20000) AS i;
CREATE INDEX posts_tags ON posts USING gin (tags);
ANALYZE posts;
EXPLAIN (COSTS OFF) SELECT count(*) FROM posts WHERE tags @> '{rare}';
EXPLAIN (COSTS OFF) SELECT count(*) FROM posts WHERE 'rare' = ANY (tags);the first uses the index; = ANY with the column on the right doesn't, because the GIN operator class only knows the array-vs-array operators. write tags @> ARRAY['rare'] when you want the index. here's the first plan run for real, on posts with a few more tags each:
GIN shows the posting lists inside.
the day it should have been a table
arrays are good for small lists you read as a unit and rarely ask questions about: a few labels, a list of scores. they go wrong when the elements start behaving like things. three signs, all real:
renaming an element touches every row that has it. retire "eco" for "green":
UPDATE products SET tags = array_replace(tags, 'eco', 'green') WHERE tags @> '{eco}';34 rows rewritten (each one a new row version, see an UPDATE is an INSERT), and a typo in one row ("Eco") goes unnoticed.
a foreign key can't point at an element. there's no way to say "every tag must exist in tags":
CREATE TABLE tag_names (name text PRIMARY KEY);
CREATE TABLE items (id int PRIMARY KEY, tags text[] REFERENCES tag_names (name));every question needs unnest first, and anything you want to know about a tag (who added it, when, its colour) has nowhere to live. the table version answers all three:
CREATE TABLE tags (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text UNIQUE NOT NULL);
CREATE TABLE product_tags (product_id int REFERENCES products, tag_id int REFERENCES tags, PRIMARY KEY (product_id, tag_id));
INSERT INTO tags (name) SELECT DISTINCT tag FROM products, unnest(tags) AS tag ORDER BY tag;
INSERT INTO product_tags SELECT p.id, t.id FROM products AS p, unnest(p.tags) AS u (tag) JOIN tags AS t ON t.name = u.tag;
UPDATE tags SET name = 'green' WHERE name = 'eco';
SELECT count(*) AS products_now_green FROM product_tags JOIN tags ON tags.id = tag_id WHERE name = 'green';| products_now_greenint8 |
|---|
| 34 |
the rename is one row. the foreign keys keep every link valid. this is first normal form arriving the practical way, and the anti-patterns chapter has more lists that wanted to be tables.
keylines
- an array is a typed list in a column, subscripted from 1.
= ANYasks about one value;@>,&&and<@compare arrays as sets.- unnest turns elements into rows, WITH ORDINALITY numbers them, array_agg goes back.
- a GIN index serves @> and &&, not = ANY.
- renaming, referencing or describing elements means it should have been a table.