Arrays
Lesson opener
In one line: When an array column is a good idea - and when a child table is better.
Why it matters: Product wants 0-N labels without a tags table on day one.
Before this lesson: Types & dialect that matter
Before you start
| Resource | Link |
|---|---|
| Previous | Types & dialect that matter |
| Next | JSONB & semi-structured data |
| Time | ~45 minutes |
What you will learn
- When an array column is a good idea — and when a child table is better
- How to write, read, search, and update
TEXT[]/INTEGER[]columns unnestfor turning arrays into rows (and back into reporting shape)- The performance instinct: arrays are not a free “stuff JSON in a column” escape hatch
When arrays help
Good fits
- Small, unordered tags:
{vip, north, email-ok} - Fixed short lists owned by one row (feature flags, roles names if not normalised yet)
- Values always fetched with the parent row
Bad fits
- Long lists you filter heavily as if they were tables
- Relationships you will join from many places — use a real junction table
- Anything that needs its own timestamps, status, or FKs per element
Rule: if you keep wanting to “join to the array element,” you wanted a table.
Create and insert
[Tag customers with a text array]
WHY: Product wants 0–N labels without a tags table on day one.
WHEN: Lightweight labelling for campaigns.
ALTER TABLE customers
ADD COLUMN IF NOT EXISTS tags TEXT[] NOT NULL DEFAULT '{}';
UPDATE customers
SET tags = ARRAY['vip', 'north']
WHERE customer_id = 'C100';
UPDATE customers
SET tags = '{standard,south}' -- literal form
WHERE customer_id = 'C200';Both ARRAY[...] and '{a,b}' literals work. Prefer ARRAY[...] in application SQL for clarity.
Search inside arrays
[Find anyone tagged vip]
SELECT customer_id, tags
FROM customers
WHERE 'vip' = ANY (tags);Contains all of a set:
SELECT customer_id, tags
FROM customers
WHERE tags @> ARRAY['vip', 'north'];Overlap (any in common):
SELECT customer_id, tags
FROM customers
WHERE tags && ARRAY['vip', 'churn-risk'];Breaking it down:
= ANY (tags)→ classic “value in array”@>→ left contains right&&→ arrays overlap
Update patterns
[Add a tag without duplicating]
UPDATE customers
SET tags = (SELECT ARRAY(SELECT DISTINCT unnest(tags || ARRAY['email-ok'])))
WHERE customer_id = 'C100';Simpler append (allows duplicates unless you prevent them):
UPDATE customers
SET tags = tags || ARRAY['email-ok']
WHERE customer_id = 'C100'
AND NOT ('email-ok' = ANY (tags));Remove one value:
UPDATE customers
SET tags = array_remove(tags, 'north')
WHERE customer_id = 'C100';unnest — arrays to rows
[Count how often each tag appears]
WHY: Managers ask for tag frequency; arrays are column-shaped, reports are row-shaped.
WHEN: Building a simple tag dashboard.
SELECT tag, COUNT(*) AS customers_with_tag
FROM customers, LATERAL unnest(tags) AS tag
GROUP BY tag
ORDER BY customers_with_tag DESC;Or:
SELECT unnest(tags) AS tag, COUNT(*)
FROM customers
GROUP BY 1
ORDER BY 2 DESC;Arrays of integers / sorting
SELECT ARRAY[3, 1, 2] AS raw,
ARRAY(SELECT unnest(ARRAY[3, 1, 2]) ORDER BY 1) AS sorted;array_length(tags, 1) returns the element count (dimension 1).
Indexing teaser
For “contains” queries on arrays you will often use a GIN index — covered properly in Index types. Do not sprinkle indexes yet; get the queries right first.
Essential commands
| Command / action | What it does | ||
|---|---|---|---|
TEXT[] / INTEGER[] | Array column types | ||
ARRAY[...] / '{a,b}' | Construct literals | ||
= ANY (arr) | Membership test | ||
@> / && | Contains / overlaps | ||
| `\ | \ | / array_remove` | Concatenate / remove element |
unnest(arr) | Expand to rows |
Practice
Do this now:
- Ensure
customers.tagsexists asTEXT[]. - Tag at least three customers with different combinations.
- Write one query with
= ANYand one with@>. - Produce a tag-frequency report with
unnest. - Save as
exercises/answers/pg/03_arrays.sql.
Teacher walkthrough: array column when it helps
All figures illustrative.
Steps: Create a text array, query with ANY/@>, and know when to prefer a child table.
Failure example
Symptom: Cannot index / update cleanly
Diagnosis: Overused arrays for relational data that needed rows.
Correction: Migrate hot filters to a normalised table; keep arrays for small tags.
Validation: Re-run the lesson's verify query/EXPLAIN snippet and confirm expected plan or result.
Guided practice
Match rows where tag list contains urgent — pattern?
Complete solution: Use @> or ANY as taught — not LIKE on array text dump.
Independent practice
Acceptance criteria:
- Completed the lesson's practice queries on your lab database.
- One failure you hit (or a simulated one) documented with fix.
- Notes state when not to use this feature.
- Link forward to the next
pglesson.
Common mistakes
- Copying MySQL dialect unchanged.
- Skipping
EXPLAINwhen performance is the claim. - Changing production without a transaction/backup habit (pg10).
Checklist
- [ ] I can explain when not to use an array
- [ ] I searched with
ANY/@>successfully - [ ] I turned tags into a frequency table with
unnest - [ ] Next: JSONB