PostgreSQL: Convert Multiple Rows to JSON

PostgreSQL: Convert Multiple Rows to JSON

novicetechie

PostgreSQL provides powerful JSON functions that allow you to convert query results into JSON format. This is especially useful for APIs and reporting.

Using json_agg()


SELECT json_agg(t)
FROM (
  SELECT id, name, role
  FROM employee
) t;

This query converts multiple rows into a single JSON array.

Output Example


[
  {"id":1,"name":"Alice","role":"Developer"},
  {"id":2,"name":"Bob","role":"Manager"}
]

The json_agg() function aggregates rows into JSON arrays efficiently.

Comments

Simple Tech Tips for Everyday Users

Learn easy tech solutions, beginner-friendly tutorials, and simple fixes for your phone, laptop, apps, and internet problems — all in one place.

Explore by Category

About NoviceTechie

NoviceTechie.com is your simple tech helper. We provide beginner-friendly tutorials, how-to guides, and easy troubleshooting tips to make technology easier for everyone — no technical knowledge required.

Latest Posts

Get Simple Tech Tips Weekly

Join our free updates (optional).

Follow Us
NoviceTechie.com — Simple tech tutorials, everyday problem fixes, and easy guides for beginners.