Brightlane's category listing endpoint needs each product represented as a structured object inside a per-category JSON array.
Write a query to return every category ID and a JSON array of objects — one per product — where each object contains the keys 'id' and 'name' for that product.
Assumptions:
- The
productstable has one row per product with anid, aname, and acategory_id. - Each
category_idwith at least one product should appear once. - For each category, the array contains one object per product. Each object has exactly two keys,
'id'and'name', populated from the product's record.
Output:
- One row per category, with columns
category_idandproducts.
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(JSON_BUILD_OBJECT('id', id, 'name', name)) AS products
FROM
products
GROUP BY
category_id The shape
jsonb_agg(json_build_object('id', id, 'name', name)) runs the inner function once per product to build a two-key JSON object, then the outer aggregate collects those objects into one JSONB array per category. The two functions compose: json_build_object shapes each row, jsonb_agg collects the shaped rows.
Clause by clause
SELECT category_id, jsonb_agg(json_build_object('id', id, 'name', name)) AS productsreturns the grouping column and the per-group array of product objects. The innerjson_build_object('id', id, 'name', name)is evaluated once for each input row, producing an object like{ "id": 14, "name": "Men's Slim Jeans" }. The outerjsonb_aggthen collects those objects across every row in the group into a single JSONB array.FROM productsreads the product records.GROUP BY category_iddefines the groups the outer aggregate works over. One distinctcategory_idper output row, with the array of that category's product objects in theproductscolumn.
Why this and not json_build_object('id', id, 'name', name) alone
Without jsonb_agg wrapping it, json_build_object runs once per row and the query returns one row per product — not one row per category. The aggregate is what collapses the per-row objects into a per-group array.
You practiced jsonb_agg(json_build_object(...)) — combine per-row object construction with per-group array aggregation; the inner json_build_object runs once per record, the outer jsonb_agg collects the results into an array.