Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 116/ 160
06. Database Design, Normalization & Semi-Structured SQL

Working with SQL Arrays (ARRAY_AGG, UNNEST, ANY, Array Operators)

Aggregate into arrays, unnest them, and use ANY/ALL array operators.

IntermediateARRAY_AGG · UNNEST3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Tag counts from an array columnQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  t.tag,3  COUNT(*) AS posts4FROM5  posts p6  CROSS JOIN UNNEST(p.tags) AS t (tag)7GROUP BY8  t.tag9ORDER BY10  posts DESC11LIMIT12  10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Most common tags3 sample rows
Most common tags
tagposts
sql18
postgres12
databases7

Note: Counts come from an illustrative posts table containing these repeated array elements.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Posts tagged both sql and postgresQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX posts_tags_gin ON posts USING gin (tags);23SELECT4  id,5  title6FROM7  posts8WHERE9  tags @> ARRAY['sql', 'postgres']::TEXT[];
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Posts containing both tags2 sample rows
Posts containing both tags
idtitle
42Indexing JSONB
105Portable SQL checks

Note: Assumes these posts have both sql and postgres in tags; array order does not matter for @>.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: @> / && with GIN for array columns; junction tables for real relationships.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Decide if an array fits

Small, read-mostly lists or parameters suit arrays; relationships needing foreign keys suit a junction table.

Focus at this step

tags text[] vs post_tags table

What to watch at this step
Integrity
junction table
Tip: use ← → to move between steps

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

Array column (text[], bigint[])
Best for: Tags, small ordered lists, parameters

Strengths: Compact; one row read; GIN-indexable.

Watch out: No foreign keys; whole value rewritten on change.

Junction table
Best for: Many-to-many relationships with integrity

Strengths: Foreign keys; link attributes; easy single-row changes.

Watch out: Extra table and joins.

JSON array
Best for: Mixed-type lists or MySQL

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?
Interview tip: Mention = ANY($1) for id lists, and @> with a GIN index for array columns. Those are the two array patterns used most in real applications.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Indexing JSONB Columns with GIN Indexes
Next topic
Full-Text Search in SQL (tsvector, tsquery, GIN Search Indexes)