Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL json_build_array: How to Use It

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Use json_build_array() in PostgreSQL to turn a list of SQL values into a JSON array. It takes any number of arguments — zero or more — and returns a single json value where each argument becomes an element in the order you supplied them. For example, SELECT json_build_array('a', 1, true); returns ["a", 1, true]. That is the whole function: no configuration, no setup, no extension. You need a PostgreSQL connection and a version that supports JSON functions (9.3 and later for the core JSON functions; jsonb variants arrived in 9.4).

What You'll Need

  • A PostgreSQL database you can run queries against (any recent major version — 12, 13, 14, 15, 16, 17 all include this function).
  • A SQL client: psql, pgAdmin, DBeaver, or any tool that lets you execute SQL.
  • Permission to run SELECT statements on the tables you reference (or just the ability to run a bare SELECT).
  • Optional: a table with columns you want to convert into arrays; otherwise you can test with literals.

Step-by-Step

  1. Connect to your database. Open psql or your GUI client and connect to the database where you want to run the query. In psql the command is \c your_database_name after connecting, or start with psql -d your_database_name.
  2. Run a minimal test. Execute SELECT json_build_array();. It returns [] — an empty JSON array. This confirms the function exists and your client displays JSON output correctly.
  3. Pass literal values. Run SELECT json_build_array('hello', 42, true, NULL);. You get ["hello", 42, true, null]. Note that SQL NULL becomes JSON null — it is not omitted.
  4. Mix data types deliberately. The function does not require matching types. json_build_array(1, '1', 1.0) returns [1, "1", 1.0] — the number, the string, and the numeric literal are preserved as written. If you need consistent types, cast first: json_build_array(1::text, '1'::text).
  5. Build arrays from table columns. Query SELECT json_build_array(id, name, created_at) FROM users LIMIT 5;. Each row produces one JSON array containing that row's three column values, in the order you listed them. The result column has type json.
  6. Nest arrays for structure. Because the function accepts any expression, you can nest calls: SELECT json_build_array('user', json_build_array(id, name)) FROM users;. This yields ["user", [1, "Alice"]]. Nesting is the standard way to build small hierarchical shapes without json_build_object.
  7. Aggregate rows into one array. A single json_build_array call handles one row. To collect many rows into one array, combine it with json_agg: SELECT json_agg(json_build_array(id, name)) FROM users;. The result is a JSON array of arrays, one inner array per row.
  8. Use it inside a larger JSON document. You can pass the result to json_build_object: SELECT json_build_object('user', json_build_array(id, name)) FROM users;. This produces {"user": [1, "Alice"]}. The two functions are designed to work together.
  9. Check the result type. Run SELECT pg_typeof(json_build_array(1, 2));. It returns json, not jsonb. If you need jsonb, cast the result: json_build_array(1, 2)::jsonb.
  10. Store or return the value. Use the expression directly in a SELECT for API responses, or insert it into a json or jsonb column: INSERT INTO logs (payload) VALUES (json_build_array('event', now()));. The column type must accept JSON; jsonb columns will cast automatically in most cases, but an explicit ::jsonb cast is safer.

Common Mistakes

  • Expecting jsonb output. json_build_array returns json. It preserves whitespace and key order, and it does not support jsonb operators like @> or ? without a cast. Cast to ::jsonb when you need those operators or indexing.
  • Assuming NULL is skipped. SQL NULL becomes JSON null and stays in the array. If you want to omit nulls, filter with WHERE col IS NOT NULL or use jsonb_strip_nulls on a jsonb cast.
  • Passing a single array argument by accident. json_build_array(ARRAY[1,2,3]) does not flatten the array. It produces [[1,2,3]] — a JSON array containing one element, which is itself a JSON array. Use to_json(ARRAY[1,2,3]) if you want [1,2,3].
  • Confusing it with array_to_json. array_to_json converts a PostgreSQL array to JSON. json_build_array builds a JSON array from separate arguments. They are not interchangeable.
  • Forgetting row context. In a query like SELECT json_build_array(id, name) FROM users, you get one array per row. If you wanted one array for all rows, you need json_agg around it.
  • Type mismatches in comparisons. Comparing a json result to a jsonb column can fail or behave unexpectedly. Cast one side explicitly.

Tips

  • Order matters. The arguments appear in the array in the exact order you write them, so list columns deliberately.
  • Use json_build_array with json_build_object to build nested documents without string concatenation.
  • For large result sets, cast to jsonb early if you plan to query inside the JSON — jsonb supports indexing and containment operators.
  • Wrap the call in COALESCE if a column may be NULL and you want a default: json_build_array(COALESCE(name, 'unknown')).
  • Use pg_typeof() to confirm what a function returns when you are unsure — it is faster than guessing.

Troubleshooting

Function does not exist. You are likely on a very old PostgreSQL version (pre-9.3) or connected to a different database than you think. Check with SELECT version(); and confirm the connection.

Output looks like a string. Some clients display JSON as text. That is a display issue, not a data issue. Run SELECT pg_typeof(json_build_array(1)); to confirm the type is json.

Unexpected nested arrays. Check whether you passed an array as a single argument. json_build_array(ARRAY[1,2]) nests; json_build_array(1, 2) does not.

Cannot use ->> or @> on the result. Those operators are for jsonb. Cast: (json_build_array(1,2))::jsonb.

Permission denied. You need SELECT on the underlying tables. Ask your database administrator or run the query against a table you own.

If that did not work, simplify: run SELECT json_build_array(); with no arguments. If that fails, the problem is the connection or version, not your query.

Frequently Asked Questions

What is the difference between json_build_array and jsonb_build_array?

json_build_array returns json; jsonb_build_array returns jsonb. The jsonb version parses the input into a binary format, which supports indexing and containment operators but does not preserve whitespace or key order.

Can json_build_array take zero arguments?

Yes. json_build_array() returns an empty JSON array [].

Does json_build_array handle NULL values?

Yes. SQL NULL becomes JSON null and remains an element in the array. It is not dropped.

How do I build one array from many rows?

Use json_agg around it: SELECT json_agg(json_build_array(id, name)) FROM users;. A bare json_build_array in the select list produces one array per row.

Can I nest json_build_array inside json_build_object?

Yes, and that is a common pattern. json_build_object('items', json_build_array(1,2,3)) produces {"items": [1,2,3]}.

Why does json_build_array(ARRAY[1,2]) return [[1,2]]?

Because the array is one argument, not two. The function treats each argument as a single element. To flatten a PostgreSQL array into a JSON array, use to_json(ARRAY[1,2]) or array_to_json(ARRAY[1,2]).