Arrays, UNNEST & generate_series
Arrays
Any type can be an array: TEXT[], INT[], DATE[]
- Literals:
'{essential,food}'orARRAY['essential', 'food'] - Indexing is 1-based:
tags[1]; slices:tags[1:2] - Length:
cardinality(tags)orarray_length(tags, 1)
Array operators
| Operator | Meaning |
|---|---|
'x' = ANY(tags) | contains element |
tags @> '{a,b}' | contains all of these (GIN-indexable) |
tags && '{a,b}' | overlaps (shares any) |
| `tags |
Functions
array_append, array_remove, array_position, array_cat, array_agg (rows → array), unnest (array → rows), array_to_string(tags, ', ')
UNNEST – array to rows ⭐
SELECT unnest(tags) FROM expenses → one row per tag. Combine with GROUP BY to count tags.
unnest(a, b) zips several arrays; WITH ORDINALITY adds a position number.
Arrays vs a junction table
- Arrays ✅ simple tag lists, small fixed lists, read mostly
- Junction table ✅ when elements need their own data, foreign keys, or are queried heavily
generate_series – generate rows
- Numbers:
generate_series(1, 10)or with a stepgenerate_series(0, 100, 10) - Dates:
generate_series('2026-11-01'::date, '2026-11-30', '1 day') - Months:
generate_series('2026-01-01'::date, '2026-12-01', '1 month')
Uses
- Fill gaps in reports: LEFT JOIN your data onto a full calendar so days with zero spending show 0 ⭐
- Test data: millions of rows in one statement
- Time slots, invoice schedules, EMI installment dates
Example
-- Arrays: query tags
SELECT title, tags, cardinality(tags) AS n_tags, tags[1] AS first_tag
FROM expenses WHERE tags && '{social,travel}' -- has social OR travel
ORDER BY amount DESC LIMIT 4;
SELECT title FROM expenses WHERE tags @> '{essential,monthly}'; -- has both
-- UNNEST: most used tags
SELECT tag, count(*) AS uses, sum(amount) AS total
FROM expenses, unnest(tags) AS tag
GROUP BY tag
ORDER BY uses DESC;
-- essential 15 | social 8 | monthly 7 ...
-- Modify arrays
UPDATE expenses SET tags = array_append(tags, 'reviewed') WHERE id = 1 RETURNING tags;
UPDATE expenses SET tags = array_remove(tags, 'reviewed') WHERE id = 1 RETURNING tags;
-- UNNEST WITH ORDINALITY
SELECT pos, item FROM unnest(ARRAY['Rent', 'Food', 'Savings']) WITH ORDINALITY AS t(item, pos);
-- generate_series: every day of the first 10 days of November, with zeros for no spending ⭐
SELECT d::date AS day,
COALESCE(sum(e.amount), 0) AS spent
FROM generate_series(DATE '2026-11-01', DATE '2026-11-10', INTERVAL '1 day') AS d
LEFT JOIN expenses e ON e.spent_on = d::date
GROUP BY d
ORDER BY d;
-- 2026-11-01 900 | 2026-11-02 8500 | ... days with nothing show 0
-- EMI schedule: 12 monthly installments of a loan
SELECT n AS installment,
(DATE '2026-12-15' + (n - 1) * INTERVAL '1 month')::date AS due_date,
round(120000 / 12.0, 2) AS amount
FROM generate_series(1, 12) AS n
LIMIT 4;
-- Test data in one statement
SELECT count(*) FROM generate_series(1, 1000000); -- 1000000