AI Hints
PostgreSQL · Lesson 39 of 120

unnest and array_agg

Rows and lists.

⏱ 2 min read▶ Video at 34:05🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

How many books have each tag? First, turn each array into rows with unnest. Then group and count. And array agg does the reverse, collecting rows into a list.

  • Array to rows
  • Count
  • Rows to array

Tag counts

Unnest makes one row per tag. Then group by tag and count. Run it. The most used tags across the shop.

query.sqlsql
SELECT tag, count(*) AS books
FROM books, unnest(tags) AS tag
GROUP BY tag
ORDER BY books DESC, tag
LIMIT 5;
Output
    tag     | books
------------+-------
 series     |     9
 bestseller |     6
 twist      |     5
 empire     |     3
 fast-paced |     3
(5 rows)

Titles per genre

Array agg collects values from many rows into one array. Order by inside it sorts the list. Run it. Each genre, with a list of its book titles.

query.sqlsql
SELECT genre, array_agg(title ORDER BY title) AS titles
FROM books
WHERE genre IN ('Cooking', 'Technology')
GROUP BY genre;
Output
   genre    |                               titles
------------+---------------------------------------------------------------------
 Cooking    | {"One Pan Dinners","Spice Roads","The Quiet Kitchen"}
 Technology | {"Data for Everyone","Python for Curious Minds","SQL in a Weekend"}
(2 rows)

Summary

Unnest turns arrays into rows, and array agg turns rows into arrays. Next, JSONB.

Key takeaways
  • unnest
  • array_agg
  • Both ways
Next up: JSONB Basics — JSON in a column