Array aggregation with ARRAY_AGG in PostgreSQL
📖 Scenario: You are managing a small bookstore database. You want to collect all book titles written by each author into a list.
🎯 Goal: Build a SQL query that groups books by author and uses ARRAY_AGG to collect all book titles for each author into an array.
📋 What You'll Learn
Create a table called
books with columns id (integer), author (text), and title (text).Insert exactly these rows into
books: (1, 'Alice Walker', 'The Color Purple'), (2, 'George Orwell', '1984'), (3, 'Alice Walker', 'Meridian'), (4, 'George Orwell', 'Animal Farm').Write a SQL query that selects
author and an array of their title values using ARRAY_AGG.Group the results by
author.💡 Why This Matters
🌍 Real World
Collecting related items into arrays is useful for reports, summaries, and data analysis in many business applications.
💼 Career
Database developers and analysts often use ARRAY_AGG to aggregate data efficiently for dashboards and applications.
Progress0 / 4 steps