Array & Nested Data Types
Arrays in SQL
Arrays let you store ordered collections within a single column — tags, skills, ordered lists. They're powerful but come with trade-offs: arrays work well for simple lists, but normalized tables are better for complex queries and joins.
- PostgreSQL —
ARRAY[],unnest(),array_agg(), GIN indexing - BigQuery —
ARRAY,UNNEST,ARRAY_AGG - Search —
@>,&&,ANY(), array containment - Transformation — unnest, aggregate, slice, replace
Arrays are perfect for denormalized storage when the collection doesn't need its own joins or filtering.
Array Operations Visualized
An array column is a value, not a relationship, and that distinction decides every design question in this lesson. When the collection is written once and read as a whole — tags on a post, roles on a user, the stop list of a route — an array keeps the row count stable and makes the read a single fetch. When elements need their own attributes, constraints, or joins to other tables, the array becomes a model you cannot normalise without a migration: a tag that needs a usage count has nowhere to live inside text[]. PostgreSQL enforces the element type strictly, so a text[] column rejects integers at insert time, and storage is one value with a length header — searching it without an index walks every element of every row.
PostgreSQL Array Fundamentals
-- Array column operations
SELECT
id,
tags,
array_length(tags, 1) AS tag_count, -- Length
tags[1] AS first_tag, -- Index (1-based!)
array_append(tags, 'new_tag') AS added,
array_remove(tags, 'deprecated') AS removed,
array_cat(tags, ARRAY['extra']) AS concatenated
FROM posts;
ℹ️
Key Insight: PostgreSQL arrays are 1-indexed (unlike most languages). Use array_length() for count, array_append()/array_remove() for modification, and unnest() to expand arrays into rows.
Two counting traps sit underneath those basics. First, array_length(tags, 1) returns NULL for an empty array instead of 0, so any count column built from it needs COALESCE; cardinality(tags) sidesteps the dimension argument and returns 0 for empty. Second, PostgreSQL arrays are multi-dimensional — ARRAY[[1,2],[3,4]] is a single value with two dimensions — and mixing dimensions in array_append is an error rather than a flattening. Slicing is inclusive at both ends, so tags[1:3] yields three elements, and an out-of-range subscript returns NULL instead of raising, which quietly poisons any concatenation that expected a string.
Unnesting Arrays
-- Expand array to rows
SELECT post_id, unnest(tags) AS tag FROM posts;
-- With ordinality for position tracking
SELECT
post_id,
tag,
ordinality AS position
FROM posts,
LATERAL unnest(tags) WITH ORDINALITY AS t(tag, ordinality);
-- Multiple arrays in parallel
SELECT post_id, t.tag, s.score
FROM posts,
LATERAL unnest(tags) AS t(tag),
LATERAL unnest(scores) AS s(score)
WHERE array_length(tags, 1) = array_length(scores, 1);
LATERAL unnest(...) WITH ORDINALITY is the shape interviewers look for: the lateral reference lets each row of posts see its own array, and ordinality preserves the author's ordering that plain unnest discards. Exploding arrays multiplies rows, so every aggregate after the join needs rechecking — a query joining a 40-element array to a 3-element array without the length guard emits 120 rows per post and inflates COUNT(*) by the same factor. When two arrays are meant to run in parallel, as with tags and scores, guard on equal length and expose position numbers, or pair them by index after both sides are unnested. A COUNT(DISTINCT tag) after the explosion is the cheapest sanity check that the join did not fan out.
Array Aggregation
-- Aggregate values into array
SELECT
department_id,
array_agg(employee_name ORDER BY salary DESC) AS employees_by_salary,
array_agg(DISTINCT skill) AS unique_skills,
array_remove(array_agg(skill), NULL) AS all_skills_no_nulls
FROM employees
GROUP BY department_id;
-- Aggregate with filtering
SELECT
department_id,
array_agg(employee_name) FILTER (WHERE salary > 80000) AS high_earners
FROM employees
GROUP BY department_id;
Ordering inside array_agg is not guaranteed unless you write it into the aggregate: array_agg(x ORDER BY y) is the only form that promises a stable sequence, and array_agg(DISTINCT x) additionally forces a sort of its own. FILTER (WHERE ...) is cheaper and clearer than a CASE expression inside the aggregate, because the engine skips non-matching rows instead of evaluating a branch for every one. NULL handling differs by function: array_agg keeps NULLs, which is why array_remove(array_agg(skill), NULL) is the standard cleanup, while array_position returns NULL when the value is absent rather than 0. Decide whether an absent element means "unset" or "unknown" before you choose the cleanup.
Array Searching
-- Check if array contains element
SELECT * FROM posts WHERE 'sql' = ANY(tags);
-- Check if array contains all elements (containment)
SELECT * FROM posts WHERE tags @> ARRAY['sql', 'interview'];
-- Check if arrays overlap
SELECT * FROM posts WHERE tags && ARRAY['sql', 'python'];
-- Array position
SELECT post_id, array_position(tags, 'sql') AS sql_position
FROM posts WHERE 'sql' = ANY(tags);
⚠️
Indexing Tip: Create a GIN index for array containment queries: CREATE INDEX idx_tags ON posts USING GIN (tags);. This significantly speeds up @> and && operations — from O(n) sequential scan to O(log n) index lookup.
The planner treats each of these operators differently once an index exists. = ANY(tags) behaves like a semi-join against an expanded array and can use a GIN index on recent PostgreSQL releases; tags @> ARRAY['sql'] is containment, which is the case GIN is built for. Selectivity decides the payoff: a tag on 60 percent of rows returns so many tuples that the index lookup costs more than it saves, while a rare tag touches a handful of posting lists instead of the whole table. For workloads that filter on both a scalar column and an array, btree_gin lets one index serve the scalar predicate and the containment predicate together.
Array Transformation
-- Transform array elements
SELECT
post_id,
array(SELECT upper(unnest(tags))) AS uppercase_tags,
array(SELECT DISTINCT unnest(tags) ORDER BY 1) AS sorted_unique,
array(SELECT unnest(tags) WHERE length(unnest(tags)) > 3) AS long_tags
FROM posts;
-- Array slicing
SELECT
post_id,
tags[1:3] AS first_three_tags, -- Elements 1-3
tags[2:] AS skip_first_tag, -- Elements 2 to end
tags[:2] AS first_two_tags -- Elements 1-2
FROM posts;
The subquery-in-select form is elegant and easy to overuse. Each array(SELECT ...) runs once per outer row, so on a million posts the statement performs a million small expansions; move the transformation into a CTE or a lateral join once the array column is large. Slices are the cheap alternative when only a preview is needed, because tags[1:3] stops work early instead of rebuilding the whole value. Repeated unnest calls in the same select list are another trap: every occurrence re-evaluates the expansion. When two derived columns need the same unnested set, compute it once in a lateral subquery and read both columns from that single result.
BigQuery Array Functions
-- BigQuery ARRAY operations
SELECT
id,
ARRAY_LENGTH(tags) AS tag_count,
tags[OFFSET(0)] AS first_tag, -- 0-indexed!
ARRAY_CONCAT(tags, ['new_tag']) AS added,
ARRAY(
SELECT DISTINCT tag
FROM UNNEST(tags) AS tag
ORDER BY tag
) AS unique_sorted_tags
FROM `project.dataset.posts`;
-- ARRAY_AGG with filtering
SELECT
department_id,
ARRAY_AGG(name ORDER BY salary DESC LIMIT 3) AS top_3_earners
FROM employees
GROUP BY department_id;
Three BigQuery differences catch anyone moving from PostgreSQL. Indexes start at zero, so tags[OFFSET(0)] is the first element while tags[ORDINAL(1)] is the same value in the PostgreSQL-friendly spelling, and omitting the accessor is an error rather than an implicit first element. ARRAY(...) wraps a scalar subquery that must return exactly one column, and UNNEST in the FROM clause is the set-returning form you use when you want one row per element alongside other columns. Cost follows bytes scanned rather than rows returned, so ARRAY_AGG(... LIMIT 3) inside a group trims the output array but does not reduce the scan that produced it.
Array Comparisons
-- Compare arrays with CASE
SELECT
post_id, tags,
CASE
WHEN tags = ARRAY['sql', 'interview'] THEN 'exact match'
WHEN tags @> ARRAY['sql'] THEN 'contains sql'
WHEN tags && ARRAY['sql', 'python'] THEN 'overlap'
ELSE 'no match'
END AS match_type
FROM posts;
A CASE over array operators reads well in reports but evaluates in order until a branch matches, so put the cheapest and most selective test first. Equality is also stricter than it looks: tags = ARRAY['a', 'b'] compares length, order and content, so ARRAY['b', 'a'] never matches, while @> ignores order and tolerates extra elements. That asymmetry explains most reports claiming containment works but equality does not. When a report needs ranking rather than a boolean, count the matched elements — for example the number of query terms present in the tag array — and sort on that count, because a two-of-three match is more informative than a flat hit.
Quiz: Test Your Knowledge
Follow-Up Questions
- When should you use arrays vs normalized tables for storing collections?
- How do you create and use custom array types in PostgreSQL?
- What's the performance impact of GIN indexes on array columns?
- How would you implement array intersection and difference operations?
- Explain the difference between
unnest()andLATERAL unnest().
Common Mistakes
Storing entities with their own attributes inside an array column
Fix: Model them as rows with a foreign key; keep arrays for collections that are only ever read as a whole
Assuming array_length returns zero for an empty array
Fix: Use cardinality for counts, or wrap array_length in COALESCE when the dimension form is required
Unnesting two arrays in parallel without checking their lengths
Fix: Guard on equal cardinality or pair elements by ordinality so the join cannot fan out silently
Creating a GIN index and expecting it to speed up every array query
Fix: Match the operator to the index: containment and overlap suit GIN, equality on one element may still prefer a scan
Key Takeaways
- PostgreSQL arrays are 1-indexed —
tags[1]is the first element unnest()expands arrays into rows;array_agg()aggregates rows into arrays- GIN index for
@>and&&operators — dramatically faster than sequential scan ANY()checks if a value exists in an array;@>checks containment- BigQuery uses 0-indexed arrays with
OFFSET(0) - Consider normalized tables when you need joins, filtering, or complex queries on array elements