Working with SQL Arrays (ARRAY_AGG, UNNEST, ANY, Array Operators)
Aggregate into arrays, unnest them, and use ANY/ALL array operators.
In plain words
An array is a list stored in one value; you can make lists from rows, and turn lists back into rows.
Think of it like…
A pill organiser with labelled compartments: one container holds several items in order, you can ask whether it contains a given pill, or tip everything out onto the table one by one.
Where you’ve seen it
An API receives up to 500 product ids and must return their prices. Instead of building a 500-placeholder IN list, the app sends one parameter: SELECT id, price FROM products WHERE id = ANY($1::bigint[]). The query text never changes, so the prepared statement is reused, and the planner uses the primary key index.
Words you’ll hear
- ARRAY_AGG
- Aggregates values into an array, optionally ordered: ARRAY_AGG(x ORDER BY y).
- UNNEST
- Expands an array into rows; WITH ORDINALITY adds each element's position.
- = ANY(array)
- True if the value equals any element; the array-friendly IN.
- @> / <@ / &&
- Contains / contained by / overlaps, between two arrays.
Visual diagram
Theory & example queries
Building and expanding arrays
ARRAY_AGG(product_id ORDER BY added_at) collects a session's products in order; add DISTINCT to drop repeats or FILTER (WHERE …) to choose which rows contribute. Note that ARRAY_AGG over zero rows returns NULL, not an empty array, so wrap it in COALESCE(…, '{}') when an empty list is expected.
UNNEST(tags) turns an array back into rows, and UNNEST(tags) WITH ORDINALITY AS t(tag, pos) keeps positions. In FROM, UNNEST behaves like a LATERAL join, so FROM posts p CROSS JOIN UNNEST(p.tags) AS t(tag) gives one row per post-tag pair, ready for GROUP BY tag. UNNEST with several arrays expands them in parallel, which is a neat way to bulk-insert columns sent as arrays.
SELECT t.tag, COUNT(*) AS postsFROM posts p CROSS JOIN UNNEST(p.tags) AS t (tag)GROUP BY t.tagORDER BY posts DESCLIMIT 10;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Most common tags3 sample rows
| tag | posts |
|---|---|
| sql | 18 |
| postgres | 12 |
| databases | 7 |
Note: Counts come from an illustrative posts table containing these repeated array elements.
Key takeaway: ARRAY_AGG collects (NULL when empty); UNNEST expands, like a lateral join.
Searching arrays, and when not to use them
'sql' = ANY(tags) tests membership for one value; tags @> ARRAY['sql', 'postgres'] requires all of them; tags && ARRAY['sql', 'mysql'] requires at least one. With CREATE INDEX ON posts USING gin (tags), @>, <@ and && become index lookups; = ANY(tags) on an array column doesn't use the GIN index, so write it as tags @> ARRAY['sql']. On the other side, id = ANY($1) with an array parameter does use an ordinary B-tree on id.
Arrays are a good fit for small, ordered or read-mostly lists. For relationships that need foreign keys, per-link attributes or frequent single-element updates, a junction table is better: arrays can't reference other tables, and changing one element rewrites the whole value. MySQL has no array type; JSON arrays with JSON_TABLE or MEMBER OF fill the gap there.
CREATE INDEX posts_tags_gin ON posts USING gin (tags);SELECT id, titleFROM postsWHERE tags @> ARRAY['sql', 'postgres']::TEXT[];PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Posts containing both tags2 sample rows
| id | title |
|---|---|
| 42 | Indexing JSONB |
| 105 | Portable SQL checks |
Note: Assumes these posts have both sql and postgres in tags; array order does not matter for @>.
Key takeaway: @> / && with GIN for array columns; junction tables for real relationships.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide if an array fits
Small, read-mostly lists or parameters suit arrays; relationships needing foreign keys suit a junction table.
tags text[] vs post_tags table
When to use it & trade-offs
What it is
PostgreSQL columns and expressions can hold arrays such as text[] or bigint[]. ARRAY_AGG collects values from many rows into one array, UNNEST expands an array back into rows, and = ANY(array) tests membership. Array operators compare whole arrays: @> (contains), <@ (is contained by), && (overlaps) and || (concatenate). Arrays are 1-based, and a GIN index makes containment and overlap queries fast.
Why it matters: Arrays show up constantly in practice: tags on a post, a list of ids passed from application code, the products in a user's session, or a path in a recursive query. They let you pass many values as one parameter and build compact per-group lists. Knowing when an array is the right tool, and when a junction table is better, is a practical design skill.
When to reach for it
- Passing lists of ids as one query parameter
- Tags and labels on read-heavy content
- Ordered per-group lists with ARRAY_AGG
When to avoid or be careful
- Arrays of foreign ids that must stay valid
- = ANY(column) expecting the GIN index to be used
- Updating single elements of huge arrays frequently
Array column vs junction table vs JSON array
Strengths: Compact; one row read; GIN-indexable.
Watch out: No foreign keys; whole value rewritten on change.
Strengths: Foreign keys; link attributes; easy single-row changes.
Watch out: Extra table and joins.
Strengths: Flexible; portable to engines without arrays.
Watch out: Weaker typing; more casting in queries.
Interview signals & numbers to know
When this topic comes up
- “Pass a list of ids to the query”
- “Posts with all of these tags”
- “Collect each user's products in order”
- UNNEST
- Arrays vs junction tables
Benchmarks & rules of thumb
- 1
- index of the first array element
- NULL
- ARRAY_AGG over zero rows
- 4
- GIN-supported array operators: @>, <@, &&, =
Common mistakes & follow-ups
Common interview mistakes
- Reading tags[0] and getting NULL, because PostgreSQL arrays start at 1.
- Building a giant IN (…) string in application code instead of passing one array with = ANY($1).
- Showing NULL tag lists for posts without tags because ARRAY_AGG returned NULL, not '{}'.
Likely interviewer follow-ups
- How would you pass 1,000 ids to a query efficiently?
- How do you find rows whose array contains all of a set of values?
- When would you choose a junction table over an array column?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Working with SQL Arrays (ARRAY_AGG, UNNEST, ANY, Array Operators) with hands-on SQL practice and interview Q&A.