Brightlane's product catalog service needs every product name in each category collected into a structured JSON array.
Write a query to return every category ID alongside a JSON array of product names for that category.
Assumptions:
- The
productstable has one row per product with anameand acategory_id. - Each
category_idwith at least one product should appear once. - For each category, the array contains every
namevalue of products in that category (one element per product, no de-duplication).
Output:
- One row per category, with columns
category_idandproduct_names.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
category_id,
JSONB_AGG(name) AS product_names
FROM
products
GROUP BY
category_id The shape
jsonb_agg(name) collects every product name in each group into a single JSONB array, so one row per category falls out of the GROUP BY carrying the array of names for that category.
Clause by clause
SELECT category_id, jsonb_agg(name) AS product_namesreturns the grouping column alongside the aggregated array.jsonb_aggruns once per group and packs everynamevalue in the group into one JSONB array, in the order the rows are encountered. The aliasproduct_namesnames the output column.FROM productsreads the product records — each row carries anameand acategory_id.GROUP BY category_idcollapses the rows to one per distinctcategory_id, which is what makesjsonb_aggproduce one array per category instead of one giant array across the whole table. Thenullcategory in the result is its own group, the same way everyGROUP BYtreats a NULL key as a distinct value.
You practiced jsonb_agg(column) — aggregate column values into a JSONB array, one element per record in each GROUP BY partition.