← Back to SQL, page 14

sql-0276 · Medium mid

How do you build a JSON object or array from query results?

SQLite has json_object(key, value, ...) for one object and json_group_array(...) to aggregate rows into an array. PostgreSQL has jsonb_build_object and jsonb_agg (or json_agg). Combining them returns nested documents, such as each customer with an array of their orders, in one query.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT c.name,
       CASE WHEN COUNT(o.id) = 0 THEN json('[]')
            ELSE json_group_array(json_object('id', o.id, 'status', o.status)) END AS orders
FROM customers c LEFT JOIN (SELECT * FROM orders ORDER BY id) o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameorders
Ana[{"id":101,"status":"shipped"},{"id":102,"status":"shipped"}]
Bilal[{"id":103,"status":"cancelled"},{"id":105,"status":"pending"}]
Chloe[{"id":104,"status":"shipped"}]
Dev[]

Each customer becomes one row with a JSON array of their orders, ordered by id. Dev has no orders; the LEFT JOIN gives one row with NULL order values, which json_group_array turns into [null] unless filtered. The CASE returns an empty array for him instead.

PostgreSQL:

sql
SELECT c.name,
       COALESCE(jsonb_agg(jsonb_build_object('id', o.id, 'status', o.status) ORDER BY o.id) FILTER (WHERE o.id IS NOT NULL), '[]'::jsonb)::text AS orders
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;
nameorders
Ana[{"id": 101, "status": "shipped"}, {"id": 102, "status": "shipped"}]
Bilal[{"id": 103, "status": "cancelled"}, {"id": 105, "status": "pending"}]
Chloe[{"id": 104, "status": "shipped"}]
Dev[]

Building JSON in the database saves round trips for API responses, but large nested documents are harder to page and cache. Keep it for small, bounded collections.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT c.name,
       CASE WHEN COUNT(o.id) = 0 THEN json('[]')
            ELSE json_group_array(json_object('id', o.id, 'status', o.status)) END AS orders
FROM customers c LEFT JOIN (SELECT * FROM orders ORDER BY id) o ON o.customer_id = c.id
GROUP BY c.id, c.name ORDER BY c.id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite: json_object and json_group_array
  • PostgreSQL: jsonb_build_object and jsonb_agg
  • Handle empty groups to avoid [null]
  • Good for small nested API responses

Common mistakes

  • Returning [null] for parents with no children
  • Building huge nested documents in one query

Follow-ups

  • How would you order elements inside the array?
  • How would you return an object keyed by id?

Tips

  • Show the empty-group handling