martyw.dev

Note ·

A common shape: fetch a flat list of rows, then group them in application code into a Map<parentId, Row[]> before returning. It works, it’s familiar, and it’s nearly always slower and more memory-hungry than asking the database to do it.

SELECT
  parent_id,
  ARRAY_AGG(id)::uuid[] AS child_ids
FROM children
WHERE parent_id = ANY($1)
GROUP BY parent_id;

One row per parent, the database handles the grouping, and the type cast keeps the application honest about what it’s getting back. MySQL has GROUP_CONCAT with the same idea. The harder ones to spot are the in-memory groupings already sitting in your codebase, doing it the slow way because that’s how it was written the first time.

Comments