Sub topic 11
When to Use an Array and When to Use a Join Table
Assume you know basic SELECT, INSERT, UPDATE, and WHERE statements. You should also understand NULL, primary keys, foreign keys, and how to create tables. This chapter focuses on choosing a design, not on learning array syntax from the beginning.
PostgreSQL arrays are useful when one column naturally contains a small, bounded collection of values. A join table is a separate table that stores one row for each relationship. Both designs can represent multiple values, but they support different rules and query patterns.
The two designs
Suppose each post can have several tags.
An array design keeps all tags in the post row:
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 ('PostgreSQL arrays', ARRAY['sql', 'postgres', 'arrays']);A join-table design uses one table for posts and another for the post-to-tag relationship:
CREATE TABLE posts (
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 post_tags (
post_id bigint NOT NULL REFERENCES posts(id) ON DELETE CASCADE,
tag_id bigint NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (post_id, tag_id)
);The join table's primary key prevents the same tag from being attached to the same post twice. Foreign keys also ensure that every relationship points to an existing post and tag.
Compare the trade-offs
| Design question | Array column | Join table |
|---|---|---|
| Small list read with the parent | Simple, one row | Requires a join or aggregate |
| Foreign key for each value | Not available for ordinary array elements | Built in |
| Extra relationship data | Awkward | Natural, add columns |
| Update one relationship | Rewrites the array value | Updates one row |
| Search by membership | Use array operators and possibly GIN | Use indexes and joins |
| Enforce uniqueness | Requires careful checks | Primary key or unique constraint |
| Preserve order | Natural array positions | Add a position column |
An array is a good fit when the values are attributes of one row, the collection is usually small, and each value does not need its own identity. Examples include a list of search terms, coordinates, or a short set of feature flags.
A join table is usually better when the values are entities, when other rows refer to them, or when the relationship has attributes. For example, a playlist's songs may need a position, an added timestamp, and a contributor. These details belong naturally on relationship rows.
Consider integrity and updates
Arrays can store invalid or inconsistent values. If tags contains text, PostgreSQL checks that each element is text, but it does not check that every tag exists in a tags table. The application must enforce that rule, or you must use triggers or another design.
Arrays also make relationship-level updates less direct:
UPDATE posts
SET tags = array_remove(tags, 'arrays')
WHERE id = 1;This is convenient for a simple list. It becomes less convenient when you need to record which user removed the tag, when the change happened, or whether the relationship has a status.
With a join table, those requirements are explicit:
ALTER TABLE post_tags
ADD COLUMN added_at timestamptz NOT NULL DEFAULT now(),
ADD COLUMN added_by bigint;
DELETE FROM post_tags
WHERE post_id = 1
AND tag_id = 3;A join table also lets you index relationship queries with ordinary B-tree indexes. Arrays can use a GIN index for containment and overlap searches, but an index does not provide relational integrity.
A practical decision process
Ask these questions before choosing:
- Does each element need a foreign key, a unique identity, or its own attributes? If yes, prefer a join table.
- Is the number of elements small and naturally bounded? If yes, an array may be suitable.
- Do you often filter, sort, group, or aggregate individual elements? A join table usually makes those queries clearer.
- Must you update one element without replacing the collection? A join table gives you a direct row-level operation.
- Does element order matter? An array preserves positions automatically. A join table needs a
positioncolumn and a suitable constraint. - Will the collection grow without a predictable limit? Prefer a join table, especially when many users or processes modify it.
The following model shows the difference in ownership.
Do not choose based only on query length
An array can make a read query shorter because the parent row already contains the values. That convenience can hide costs. A large array increases the size of the row, complicates validation, and can cause concurrent updates to contend on the same row.
A normalized join table often requires more SQL, but it provides clearer constraints and better control over individual relationships. It is the safer default for many-to-many data, shared entities, and collections that will gain behavior over time.
Use an array when the collection is simple, owned by one row, and usually consumed as a whole. Use a join table when the elements or their relationships have independent meaning.
Exercise
A customer has a short list of preferred interface languages. No other table refers to the languages, and the application reads the whole list with the customer. Should you start with an array or a join table, and why?
Show answer
Start with an array. The list is small, belongs directly to the customer, and has no independent relationship data. Choose a join table later if languages need foreign keys, metadata, ordering rules, or independent queries.