Using FOREACH to Iterate Over Arrays in PostgreSQL
📖 Scenario: You are managing a small library database. Each book has a list of genres stored as an array. You want to process each genre for every book to prepare reports.
🎯 Goal: Build a PostgreSQL function that uses FOREACH to iterate over an array of genres for a book and insert each genre into a separate table for reporting.
📋 What You'll Learn
Create a table
books with columns id (integer) and genres (text array).Create a table
book_genres with columns book_id (integer) and genre (text).Write a function
process_book_genres that takes a book id and uses FOREACH to iterate over the genres array of that book.Inside the loop, insert each genre into the
book_genres table with the corresponding book_id.💡 Why This Matters
🌍 Real World
Many databases store lists or tags as arrays. Using FOREACH helps process each item individually for reporting or further analysis.
💼 Career
Database developers and administrators often write functions to manipulate array data efficiently using loops like FOREACH in PostgreSQL.
Progress0 / 4 steps