// aggregates reference

SQL ARRAY_AGG function

Gathers every value of a group into one array, in the order you choose. Unlike STRING_AGG you get typed elements you can index, unnest or turn into JSON.

カテゴリ
Aggregates
Returns
array of the expression's type
In this category
8 of 52

構文

ARRAY_AGG(expression ORDER BY ...)  -- PostgreSQL

エンジンサポート

エンジンSupportメモ
SQL Server Not built in no array type; STRING_AGG, or JSON_ARRAYAGG on SQL Server 2025 and Azure SQL
PostgreSQL はい Supported under this name.
MySQL Not built in no array type; JSON_ARRAYAGG returns a JSON array
SQLite Not built in no array type; json_group_array returns a JSON array
Oracle Not built in no ARRAY_AGG; JSON_ARRAYAGG (12.2+) or COLLECT into a collection type

例

PostgreSQL

SELECT customer_id,
       ARRAY_AGG(product ORDER BY product) AS basket
FROM order_items
GROUP BY customer_id;

PostgreSQL

-- and back to one row per element
WITH baskets AS (
  SELECT customer_id, ARRAY_AGG(product) AS basket
  FROM order_items GROUP BY customer_id
)
SELECT customer_id, unnest(basket) AS product FROM baskets;

知っておくと便利なこと

  • ARRAY_AGG returns NULL for an empty group. Wrap it in COALESCE(ARRAY_AGG(x), '{}') when you need an empty array.
  • NULL values are kept as elements: two NULL rows give {NULL,NULL}. Add FILTER (WHERE x IS NOT NULL) to drop them.
  • Without ORDER BY inside the call the element order is whatever order the rows arrived in. Write ARRAY_AGG(product ORDER BY product) when order matters.

Questions about ARRAY_AGG

Does SQL Server have ARRAY_AGG?

No. SQL Server has no array type. STRING_AGG builds delimited text, FOR JSON builds JSON from a query, and SQL Server 2025 adds JSON_ARRAYAGG.

How do I get an array in MySQL or SQLite?

Neither has arrays. MySQL's JSON_ARRAYAGG and SQLite's json_group_array both collect values into a JSON array, which covers most of the same ground.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.