Sub topic 3
Converting between arrays and rows
This chapter assumes you can write SELECT with GROUP BY, know how a text[] column works, and have the posts table with a tags text[] column from earlier chapters.
Converting between arrays and rows
unnest turns one array into one row per element. WITH ORDINALITY adds each element's 1-based position.
SELECT p.id, t.tag, t.pos
FROM posts AS p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS t(tag, pos);Once the elements are rows, you can count and group them:
SELECT tag, count(*) AS uses
FROM posts, unnest(tags) AS tag
GROUP BY tag
ORDER BY uses DESC, tag;To go the other way, array_agg collects rows into one array, and ARRAY(subquery) builds an array from a subquery's result:
SELECT array_agg(DISTINCT tag ORDER BY tag) AS all_tags
FROM posts, unnest(tags) AS tag;
SELECT ARRAY(SELECT title FROM posts ORDER BY id) AS titles;Speeding up array searches with GIN indexes
A plain B-tree index does not help with containment checks like tags @> ARRAY['postgres']. A GIN (Generalized Inverted Index) stores each element and the rows that contain it, so it can find matching rows quickly.
CREATE INDEX posts_tags_gin ON posts USING gin (tags);
EXPLAIN SELECT title FROM posts WHERE tags @> ARRAY['postgres'];The planner may still choose a sequential scan on a small table. That choice is correct for small data, so check EXPLAIN on realistic row counts.
Multidimensional arrays and their limits
PostgreSQL accepts nested arrays, but the declared type does not enforce the shape. int[] and int[][] are the same type. Each sub-array must have the same length:
SELECT array_dims('{{1,2},{3,4}}'::int[]); -- [1:2][1:2]
SELECT ARRAY[[1,2],[3]]; -- ERROR: mismatched sub-array lengthsMost application code avoids nested arrays because they are hard to query and index.
> Hmm
When to use an array and when to use a join table
Use an array column for a short, unordered list that you read and write with the row, such as a few labels. Use a join table when you need constraints, foreign keys, or per-item data:
CREATE TABLE post_tags (
post_id bigint REFERENCES posts (id) ON DELETE CASCADE,
tag text NOT NULL,
PRIMARY KEY (post_id, tag)
);A join table enforces that each tag exists once per post and lets other tables reference tags.
Exercise
Write a query that returns each distinct tag and the number of posts using it, sorted by name, using a single pass over posts.
Show answer
SELECT tag, count(*) AS uses FROM posts, unnest(tags) AS tag GROUP BY tag ORDER BY tag;