Part 14 / Topic 1 of 10
Arrays
Any type can be an array type. Right where Part 9 said "no lists in columns (1NF)", arrays are the carve-out: a list that really is one atomic fact about the row — tags, phone numbers, RGB channels — can live honestly in one:
CREATE TABLE promo_bundles (
bundle_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
product_ids integer[] NOT NULL
);
INSERT INTO promo_bundles (name, product_ids) VALUES
('Work-from-home kit', ARRAY[1, 9, 10]),
('Reader''s corner', ARRAY[5, 6, 9]);
SELECT name, product_ids[1] AS first_item, cardinality(product_ids) AS items
FROM promo_bundles;
CREATE TABLE
INSERT 0 2
name | first_item | items
--------------------+------------+-------
Work-from-home kit | 1 | 3
Reader's corner | 5 | 3
(2 rows)
(One-based indexing — SQL tradition.) The two workhorses: ANY asks "is this value in the array?", and unnest explodes the array back into rows, where the whole relational toolkit applies:
SELECT name FROM promo_bundles WHERE 9 = ANY (product_ids);
name
--------------------
Work-from-home kit
Reader's corner
(2 rows)
SELECT b.name AS bundle, p.name AS product
FROM promo_bundles AS b
CROSS JOIN LATERAL unnest(b.product_ids) AS u(product_id)
JOIN products AS p ON p.product_id = u.product_id
ORDER BY b.bundle_id, p.product_id;
bundle | product
--------------------+--------------------
Work-from-home kit | Laptop Pro 14
Work-from-home kit | Desk Lamp
Work-from-home kit | USB-C Cable
Reader's corner | SQL for Beginners
Reader's corner | Postgres Deep Dive
Reader's corner | Desk Lamp
(6 rows)
The honest line between this and a junction table: arrays carry no foreign-key enforcement (a bundle could list product 999 and nothing would object), and querying "which bundles hold product 9" at scale wants the junction's indexes. Display lists and small atomic facts belong in arrays; real relationships still belong in Part 9's junction table.
🧪 Quick quiz — answer from memory, then check.
- How do you filter rows whose array contains the value 9?
- What does the array column not give you that a junction table does?
Show the answers
WHERE 9 = ANY (product_ids).- Foreign-key integrity on the members (and easy indexed reverse lookups).
Done here? The practice set for Part 14 — 6 exercises with solutions — is on the part page.