Knowledge base / SQL
ARRAY_AGG in PostgreSQL: order, NULL and value lists
Small synthetic examples explain duplicates, missing elements and ordering, while distinguishing PostgreSQL arrays from JSON.

When I need one list of values per group, I use array_agg in PostgreSQL. Its result is a typed array. This entry uses PostgreSQL 18 and integers to make order and duplicates easy to follow. The examples are synthetic. I derive their results from the documentation and by tracing the input rows, rather than presenting them as output from an executed database session.
Collect a list for each group
The aggregate reference describes collecting values, including NULL. The default element order is unspecified, so I state the order inside the call. Repeated values remain present.
WITH items(group_id, seq, code) AS (
VALUES (1, 1, 20), (1, 2, 10), (1, 3, 20), (2, 1, 30)
)
SELECT group_id, array_agg(code ORDER BY seq) AS codes
FROM items
GROUP BY group_id
ORDER BY group_id;
| group_id | codes |
|---|---|
| 1 | {20,10,20} |
| 2 | {30} |
For group 1, positions 1, 2 and 3 yield 20, 10 and 20 again. The outer ORDER BY group_id orders groups; the inner ORDER BY seq orders elements. If seq were not unique within a group, I would need another key to break ties for a stable order. Physical record order is not a reliable agreement about the list’s contents.
DISTINCT answers a different question
For unique codes, I use:
WITH items(code) AS (VALUES (20), (10), (20))
SELECT array_agg(DISTINCT code ORDER BY code) AS codes
FROM items;
The result is {10,20}. PostgreSQL’s aggregate-expression rules require ordering expressions to belong to the DISTINCT list when combining these features. I do not attempt to order distinct codes by a separate seq field here.
Before removing duplicates, I ask what repetition means. If a code appears in two order lines, removing an occurrence changes the question. If I need the set of different codes, removing repetition is intentional. I do not add DISTINCT automatically to conceal a multiplying join. I first check the relationship and how many input rows should actually belong to each group.
Distinguish NULL, an empty array and an absent group
These are different situations. Aggregating one NULL produces {NULL}. Aggregating no input rows produces NULL, which can be replaced with an empty array. A grouped query over entirely empty input does not create an otherwise absent group.
WITH items(code) AS (VALUES (10), (NULL::integer), (20))
SELECT
array_agg(code ORDER BY code) AS with_missing,
array_agg(code ORDER BY code)
FILTER (WHERE code IS NOT NULL) AS without_missing
FROM items;
The first column is {10,20,NULL}; the second is {10,20}. In this ascending order, NULL comes last. When no row passes the filter, I can deliberately choose an empty list:
WITH items(code) AS (VALUES (NULL::integer))
SELECT COALESCE(
array_agg(code) FILTER (WHERE code IS NOT NULL),
ARRAY[]::integer[]
) AS codes
FROM items;
The result is {}. The explicit type identifies an integer array. FILTER selects input for this aggregate, which differs from removing a whole group through WHERE. With a LEFT JOIN, the filtering rule should reflect the meaning of the data: an unmatched record and an existing record containing a missing value may need different treatment.

A row limit does not limit each array
I do not append LIMIT 10 to a grouped query expecting it to shorten every array. That limit applies to result rows. Selecting the first ten elements in each group needs a separate rule before aggregation, such as numbering rows within groups and filtering them. Slicing a finished array still constructs the full array first. Those approaches differ in both meaning and the work the database must perform.
For a small exercise, define the input range and inspect the result’s length. The cardinality function returns the number of elements, including zero for an empty array. I make no performance promise merely because an aggregate is used. Large lists need an assessment of the actual query and recipient’s needs. Sometimes a detail table remains the more useful result format.
PostgreSQL arrays, JSON and text
{20,10} represents a PostgreSQL array, while [20,10] can represent a JSON array. They are different types. MySQL 8.4 documents JSON_ARRAYAGG, with different syntax and ordering rules. The queries above should not be copied there as direct equivalents. If the recipient needs a string, choose text aggregation explicitly rather than treating comma-separated text as a structured array.
Text-array display also depends on its values: text containing special characters may need double quotes. Do not wrap every displayed element in SQL-style single quotes. For practice, choose three codes, a duplicate and a missing value, then write the expected results for ordinary aggregation, DISTINCT and FILTER. Continue with GROUP BY and LEFT JOIN to understand the rows entering the list.
Key takeaways
Does ARRAY_AGG work the same way in MySQL?
No. These examples use PostgreSQL 18. MySQL 8.4 has JSON_ARRAYAGG, which returns JSON and uses different syntax.
Does ARRAY_AGG skip NULL?
For scalar values in PostgreSQL, NULL elements are retained. Use FILTER to exclude them when appropriate.
Does LIMIT 10 restrict each array to ten elements?
No. An outer LIMIT restricts result rows. Array elements need a separate restriction, for example before aggregation.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
