1 min read

json_agg & array_agg

json_agg & array_agg
Photo by Sunder Muthukumaran / Unsplash

Misalkan punya struktur data many to many seperti ini:

  • table Post
  • table Tag
  • table tag_post

Kita bisa menggunakan query berikut

SELECT post.title, tag.name
FROM post
LEFT JOIN tag_post ON post.id = tag_post.post_id
LEFT JOIN tag ON tag_post.tag_id = tag.id;

Hasilnya seperti berikut

id title tag
1 Title tag 1
1 Title tag 2
2 Title 2 tag 3
3 Title 3 NULL

Tapi bagaimana kalau kita ingin informasinya tidak berulang dan hasilnya tag tersebut cukup menjadi 1 field.

Kita bisa menggunakan json_agg dan array_agg

json_agg

select post.id, post.title, json_agg("tag"."name") as tag
from post
LEFT join  tag_post on tag_post.post_id = post.id
LEFT JOIN tag on tag_post.tag_id = tag.id
GROUP by post.id

hasilnya

id title tag
1 Title ["tag1", "tag2"]
2 Title 2 ["tag3"]
3 Title 3 [null]

atau array_agg

select post.id, post.title, array_agg("tag"."name") as tag
from post
LEFT join  tag_post on tag_post.post_id = post.id
LEFT JOIN tag on tag_post.tag_id = tag.id
GROUP by post.id

hasilnya

id title tag
1 Title {tag1, tag2}
2 Title 2 {tag3}
3 Title 3 {NULL}