skip to content

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.

ARRAY['eco', 'new', 'sale', 'gift']
eco
1
new
2
sale
3
gift
4
real output, postgres 18.6 (PGlite 0.5.12) · arrays
a four-element array with its subscripts. 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:

sqlempty db
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;
output, from postgres 18.6
SELECT 1
constructortext[]literaltext[]trickytext[]sliceint4[]
{eco,new}{eco,new}{"left handed",NULL,"NULL",""}{20,30}
(1 row)

"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:

sqlempty db
SELECT cardinality('{}'::int[]) AS cardinality, array_length('{}'::int[], 1) AS array_length;
output, from postgres 18.6
SELECT 1
cardinalityint4array_lengthint4
0null
(1 row)

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:

WHERE =
tags.sql
  1. 1SELECT id, name, tags FROM products WHERE 'steel' = ANY (tags) ORDER BY id LIMIT 6;
the result for = ANY
idint4nametexttags_text
1chef's knife{steel,sharp}
6hose reel{steel}
(2 rows)

= ANY: steel is one of the elements.

real output, postgres 18.6 (PGlite 0.5.12) · arrays
the same table, four questions. pick an operator. = ANY tests one value against the list, the other three compare two whole arrays as sets, so order and repeats don't matter.
predict the output
sql
SELECT 3 = ANY (ARRAY[1, NULL]);
sqlempty db
SELECT 3 = ANY (ARRAY[1, NULL]) AS not_found, 1 = ANY (ARRAY[1, NULL]) AS found, 'x' = ANY ('{}'::text[]) AS empty_list;
output, from postgres 18.6
SELECT 1
not_foundboolfoundboolempty_listbool
nulltf
(1 row)

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:

idtags
1{steel,sharp}
3{}
5{wired,closed-back}
7{wood,kids}
(4 rows)
idtagpos
1steel1
1sharp2
5wired1
5closed-back2
7wood1
7kids2
(6 rows)
real output, postgres 18.6 (PGlite 0.5.12) · arrays
four products before and after unnest. each element becomes a row, numbered by 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):

sqldb=shop
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;
output, from postgres 18.6
SELECT 4
tagtextproductsint8some_idsint4[]
new68{16,17,22,23,24}
eco34{16,22}
sale33{10,20,27}
outdoor10{12,21,29}
(4 rows)

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 =:

sqlempty db
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);
output, from postgres 18.6
#1 · SELECT 20000
#2 · CREATE INDEX
#3 · ANALYZE
#4 · EXPLAIN
Aggregate -> Bitmap Heap Scan on posts Recheck Cond: (tags @> '{rare}'::text[]) -> Bitmap Index Scan on posts_tags Index Cond: (tags @> '{rare}'::text[])
#5 · EXPLAIN
Aggregate -> Seq Scan on posts Filter: ('rare'::text = 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:

show =
actual rows
real output, postgres 18.6 (PGlite 0.5.12) · arrays
EXPLAIN ANALYZE of a containment query on 20,000 posts. the bitmap index scan on the GIN index finds exactly the 206 matching rows, and the heap scan only visits those.

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":

sqldb=shop
UPDATE products SET tags = array_replace(tags, 'eco', 'green') WHERE tags @> '{eco}';
output, from postgres 18.6
UPDATE 34

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":

sqlempty db
CREATE TABLE tag_names (name text PRIMARY KEY);
CREATE TABLE items (id int PRIMARY KEY, tags text[] REFERENCES tag_names (name));
output, from postgres 18.6
#1 · CREATE TABLE
#2 · ERROR 42804
ERROR 42804: foreign key constraint "items_tags_fkey" cannot be implemented
DETAIL: Key columns "tags" of the referencing table and "name" of the referenced table are of incompatible types: text[] and text.

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:

sqldb=shop
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';
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · INSERT 0 22
#4 · INSERT 0 202
#5 · UPDATE 1
#6 · SELECT 1
products_now_greenint8
34
(1 row)

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.
  • = ANY asks 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.