Rana Maninder Singh
Lesson 3 of 11PostgreSQL

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

ResourceLink
PreviousTypes & dialect that matter
NextJSONB & 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
  • unnest for 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

Bad fits

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:


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 / actionWhat 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:

  1. Ensure customers.tags exists as TEXT[].
  2. Tag at least three customers with different combinations.
  3. Write one query with = ANY and one with @>.
  4. Produce a tag-frequency report with unnest.
  5. 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:

Common mistakes

  1. Copying MySQL dialect unchanged.
  2. Skipping EXPLAIN when performance is the claim.
  3. 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