Sub topic 11
When to Use an Array and When to Use a Join Table
This chapter assumes you know the array operators from earlier in the tutorial (@>, &&, ANY, unnest, array_agg) and can read a basic EXPLAIN plan. It also assumes you know foreign keys and primary keys. Here you will compare two designs for the same data, see where each one breaks down, and pick one with explicit criteria.
The same data in two shapes
Suppose each post has tags. There are two common ways to model that.
Array design. The tags live in a text[] column on the post. This is the posts table you used in earlier chapters:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);Join table design. Tags are rows in their own table. A third table, the join table (also called a junction or association table), links posts to tags. Each row in it is one post-tag pair.
CREATE TABLE articles (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL
);
CREATE TABLE tags (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE
);
CREATE TABLE article_tags (
article_id bigint NOT NULL REFERENCES articles (id) ON DELETE CASCADE,
tag_id bigint NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
added_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (article_id, tag_id)
);
CREATE INDEX article_tags_tag_id_idx ON article_tags (tag_id);
INSERT INTO articles (title) VALUES ('Intro to arrays'), ('Indexing');
INSERT INTO tags (name) VALUES ('sql'), ('postgres'), ('indexing'), ('gin');
INSERT INTO article_tags (article_id, tag_id)
SELECT a.id, t.id
FROM (VALUES
('Intro to arrays', 'sql'),
('Intro to arrays', 'postgres'),
('Indexing', 'postgres'),
('Indexing', 'indexing'),
('Indexing', 'gin')
) AS v(title, tag)
JOIN articles AS a ON a.title = v.title
JOIN tags AS t ON t.name = v.tag;The primary key on (article_id, tag_id) already gives you an index for "which tags does this article have". The extra index on tag_id serves the opposite direction, "which articles have this tag".
How common tasks compare
Most day-to-day operations are possible in both designs. The difference is how much work each one takes and what the database guarantees for you.
Finding rows with one tag:
-- Array design
SELECT title FROM posts WHERE tags @> ARRAY['postgres'];
-- Join table design
SELECT a.title
FROM articles AS a
JOIN article_tags AS at ON at.article_id = a.id
JOIN tags AS t ON t.id = at.tag_id
WHERE t.name = 'postgres';Finding rows that have all of several tags:
-- Array design
SELECT title FROM posts WHERE tags @> ARRAY['postgres', 'gin'];
-- Join table design
SELECT a.title
FROM articles AS a
JOIN article_tags AS at ON at.article_id = a.id
JOIN tags AS t ON t.id = at.tag_id
WHERE t.name IN ('postgres', 'gin')
GROUP BY a.id, a.title
HAVING count(*) = 2;Renaming a tag everywhere:
-- Array design: finds and rewrites every affected row
UPDATE posts
SET tags = array_replace(tags, 'postgres', 'postgresql')
WHERE tags @> ARRAY['postgres'];
-- Join table design: one row changes
UPDATE tags SET name = 'postgresql' WHERE name = 'postgres';The array version is shorter for reads. The join table version is shorter for tag-wide changes, and the gap grows with the number of rows that use the tag.
What the array design costs you
No referential integrity on elements
PostgreSQL does not support foreign keys on array elements. Nothing stops a typo such as 'postgress' from entering the column, and nothing removes a tag from every array when the tag is retired. If the allowed values are a small fixed list, a CHECK constraint gives partial protection:
ALTER TABLE posts
ADD CONSTRAINT posts_tags_known
CHECK (tags <@ ARRAY['sql', 'postgres', 'indexing', 'gin', 'tutorial']);The list is now hard-coded in the schema, so adding a tag requires a migration. A tags table lets you add a tag with an INSERT.
Duplicates, ordering, and NULL elements
An array happily stores {sql,sql} and {sql,NULL}. A join table with a composite primary key rejects duplicate pairs and NOT NULL columns reject missing values. With arrays you must enforce these rules yourself, either in application code or with constraints such as CHECK (array_position(tags, NULL) IS NULL).
Arrays do keep order, which a join table does not unless you add a position column. If order matters (for example, a ranked list), that is a point in favor of arrays.
Declared sizes are also not enforced. text[3] behaves exactly like text[], so the declared length does not limit how many elements a row can hold.
Whole-value updates
An array is a single column value. Changing one element with array_append or array_replace builds a new array and writes a new version of the whole row. This follows from PostgreSQL's MVCC (multi-version concurrency control), which never edits a row in place. For a five-element array this is negligible. For an array with thousands of elements, larger values are compressed or moved to TOAST storage (out-of-line storage for big values), and each append rewrites the whole value.
Concurrency is also coarser. Two sessions appending to the same row's array queue behind the row lock. Two sessions inserting different rows into a join table do not block each other.
Weaker statistics
The planner keeps statistics about array columns, but its estimates for @> and && are rougher than its estimates for an equality match on an indexed tag_id. If a query on an array column picks a poor plan, check EXPLAIN (ANALYZE) and compare estimated and actual row counts.
Index maintenance
A GIN index (covered earlier in this tutorial) makes array searches fast, but GIN indexes are more expensive to update than B-trees. Each row change touches an index entry per element. A write-heavy table with long arrays pays for that. A join table with a B-tree on tag_id has cheaper individual writes, and each one touches a small row.
What the join table costs you
- More tables, more joins, and more SQL to write. Reading a post with its tags needs a join or a subquery.
- Extra storage. Each pair is a full row with its own header (about 24 bytes) plus the key columns and index entries. A short array on the parent row is usually smaller.
- Inserting a post with tags takes several statements, or one statement with data-modifying CTEs.
- The "has all of these tags" query needs
GROUP BY ... HAVING count(*), which is easy to get subtly wrong (for example, forgettingDISTINCTwhen duplicates are possible).
Reading the join table as an array
You can combine the two designs. Keep the join table as the source of truth and build arrays on demand with ARRAY(subquery):
SELECT a.id,
a.title,
ARRAY(
SELECT t.name
FROM article_tags AS at
JOIN tags AS t ON t.id = at.tag_id
WHERE at.article_id = a.id
ORDER BY t.name
) AS tags
FROM articles AS a;This gives application code a convenient array while the database keeps integrity, uniqueness, and per-link columns like added_at. Wrapping it in a view makes it reusable. The reverse is also possible: keep an array column as a read-optimized copy, maintained by triggers. That adds complexity and a risk of drift, so do it only when profiling shows the join is a real bottleneck.
A decision flow
Decision criteria in a table
| Question | Favors an array | Favors a join table |
|---|---|---|
| What are the elements? | Plain values (labels, phone numbers, scores) | Entities with a name, id, or other columns |
| Who owns them? | Only this row | Shared by many rows (many-to-many) |
| Integrity rules | Few; a `CHECK` is enough | Foreign keys, uniqueness, cascades |
| Data per relationship | None | Timestamps, roles, positions, weights |
| Typical access | Read or written as a whole list | Per-element inserts, updates, deletes |
| Size per row | Small and bounded (a handful to a few hundred) | Large or unbounded |
| Reporting | Occasional element counts | Frequent counts, rankings, joins by element |
| Element order | Must be preserved, no extra column | Order is irrelevant, or a position column is fine |
| Portability | PostgreSQL only is acceptable | Must run on other databases or ORMs |
Good fits for arrays
- A list of labels on a document that you always load together with the row, such as
tagsfor a small blog. - Application settings stored as a list of values, such as
allowed_ips inet[], where each value has no identity of its own. - Short ordered lists such as a
{lat,lon}pair or a set of recent scores, where the list is replaced or appended as a unit. - Staging data: loading a batch parameter as an array and expanding it with
unnestin a query, without storing it.
Good fits for join tables
- Users and roles, students and courses, products and categories: relationships where either side is queried independently.
- Anything needing a foreign key, such as tag names that must exist in a managed
tagstable. - Relationships carrying data, such as when a tag was added or who added it.
- Any list that can grow without a clear bound, such as followers or order lines.
Migrating between designs
Moving from an array to a join table is a standard unnest job:
INSERT INTO tags (name)
SELECT DISTINCT tag
FROM posts, unnest(tags) AS tag
ON CONFLICT (name) DO NOTHING;After the tags exist, insert the pairs by joining the unnested arrays to tags on name. Because unnest produces one row per element, the same query shape works for any array-to-rows conversion. Going the other way, array_agg grouped by the parent id rebuilds arrays from pairs. Both directions are routine, so choosing arrays first is not a trap. The cost grows as more code depends on the array shape.
Exercises
Exercise
A products table needs a list of the product's size options (S, M, L, XL). The list has at most six entries, never changes after the product is created, and is always shown together with the product. Array column or join table? Name two reasons.
Show answer
An array column (text[]) fits. The elements are plain values with no attributes of their own, the list is small and bounded, and it is read and written as a unit. A CHECK (sizes <@ ARRAY['XS','S','M','L','XL','XXL']) can restrict the allowed values. A join table would add two tables and a join for no gain.
Exercise
A courses table needs to record which students are enrolled, along with each enrollment date and a final grade. A teammate suggests student_ids bigint[] on courses. List three problems with this design and describe the alternative.
Show answer
(1) Array elements cannot have foreign keys, so the database cannot ensure each id refers to a real student or clean up when a student is deleted. (2) Enrollment date and grade are per-link data with no place to live in a plain array. (3) Updating one student's grade, or counting courses per student, means rewriting or unnesting the whole array. Use an enrollments join table with course_id, student_id, enrolled_on, and grade, with a composite primary key on (course_id, student_id) and foreign keys to both parent tables.
Exercise
You have a join table article_tags and want one row per article with its tag names as a sorted array, without changing the schema. Write the query.
Show answer
SELECT a.id, a.title, ARRAY(SELECT t.name FROM articletags AS at JOIN tags AS t ON t.id = at.tagid WHERE at.article_id = a.id ORDER BY t.name) AS tags FROM articles AS a; The ARRAY(subquery) constructor builds the array from the ordered subquery rows, and an article with no tags gets an empty array rather than NULL.