Skip to content

Commit 6753f1d

Browse files
committed
Document ARRAY_AGG()
* Add a page about the `ARRAY_AGG()` aggregate function to the SQL Reference. * Drop the `array-agg-correlated-subquery` block from `array-agg-tests.yamsql`, along with the `parent` and `child` tables it used, since the new documentation-queries file covers the correlated-subquery forms.
1 parent 18da484 commit 6753f1d

6 files changed

Lines changed: 287 additions & 27 deletions

File tree

docs/sphinx/source/reference/Aggregates.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ This section documents the system-defined **aggregate functions**. These functio
99
.. toctree::
1010
:maxdepth: 1
1111

12+
Functions/aggregate_functions/array_agg
1213
Functions/aggregate_functions/avg
1314
Functions/aggregate_functions/bitmap_construct_agg
1415
Functions/aggregate_functions/count
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Diagram(
2+
Terminal('ARRAY_AGG'),
3+
Terminal('('),
4+
NonTerminal('expression'),
5+
Optional(
6+
Sequence(
7+
Choice(0,
8+
Terminal('IGNORE'),
9+
Terminal('RESPECT'),
10+
),
11+
Terminal('NULLS'),
12+
),
13+
'skip'
14+
),
15+
Terminal(')'),
16+
)
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
=========
2+
ARRAY_AGG
3+
=========
4+
5+
.. _array-agg:
6+
7+
Collects the values of an expression across the rows of a group into a single array.
8+
9+
Syntax
10+
======
11+
12+
.. raw:: html
13+
:file: array_agg.diagram.svg
14+
15+
Parameters
16+
==========
17+
18+
``expression``
19+
The value collected from each row of the group. May be of any type except ``ARRAY``. The result is an array of the argument’s type.
20+
21+
``ALL``
22+
Collects every value of ``expression``, which is the default behavior when no set quantifier is present.
23+
24+
``IGNORE NULLS``
25+
Causes ``NULL`` values of ``expression`` to be omitted from the resulting array.
26+
27+
``RESPECT NULLS``
28+
Causes ``NULL`` values of ``expression`` to be collected as array elements. This is the default when no null-treatment clause is present.
29+
30+
Returns
31+
=======
32+
33+
Returns an array whose elements are the values of ``expression`` in the group. The order of elements within the array is unspecified.
34+
35+
The element type of the array is non-nullable when ``IGNORE NULLS`` is used, or when ``expression`` itself is non-nullable. Otherwise (that is, for a nullable ``expression`` with ``RESPECT NULLS`` behavior, which is the default) the element type is nullable. (However, see the note below regarding a current limitation on ``NULL`` elements in arrays.)
36+
37+
The behavior on empty input depends on whether a ``GROUP BY`` clause is present:
38+
39+
* Without ``GROUP BY``, aggregating over an empty input returns a single row whose array value is ``NULL``.
40+
* With ``GROUP BY``, aggregating over an empty input returns no rows.
41+
42+
A group that does contain rows, but whose ``expression`` values are all ``NULL``, returns an empty array ``[]`` rather than ``NULL`` under ``IGNORE NULLS``. This holds whether or not a ``GROUP BY`` clause is present.
43+
44+
Examples
45+
========
46+
47+
Setup
48+
-----
49+
50+
For these examples, assume we have a ``sales`` table:
51+
52+
.. code-block:: sql
53+
54+
CREATE TABLE sales (
55+
id BIGINT,
56+
product STRING,
57+
region STRING,
58+
amount BIGINT,
59+
PRIMARY KEY (id)
60+
)
61+
62+
CREATE INDEX product_idx AS SELECT product FROM sales ORDER BY product
63+
64+
INSERT INTO sales VALUES
65+
(1, 'Widget', 'North', 100),
66+
(2, 'Widget', 'South', 150),
67+
(3, 'Gadget', 'North', 200),
68+
(4, 'Gadget', 'South', NULL),
69+
(5, 'Widget', 'North', 120)
70+
71+
The ``product_idx`` index is needed for the ``GROUP BY product`` query to be planned; see the note on required indexes under :ref:`Important Notes <array-agg-important-notes>`.
72+
73+
Collecting all values
74+
---------------------
75+
76+
The following query collects all amounts in the table into a single array.
77+
78+
.. code-block:: sql
79+
80+
SELECT ARRAY_AGG(amount IGNORE NULLS) AS amounts FROM sales
81+
82+
.. list-table::
83+
:header-rows: 1
84+
85+
* - :sql:`amounts`
86+
* - :json:`[200, 100, 150, 120]`
87+
88+
Note that the ``NULL`` value in row 4 is omitted from the array.
89+
90+
Note also that the elements do not appear in ``id`` order. They are collected in whatever order the rows happen to be read in, and here the query is served by a scan of ``product_idx``, which visits the ``Gadget`` row before the ``Widget`` rows. Adding or removing an index may therefore change the order of the elements within the array.
91+
92+
ARRAY_AGG() with GROUP BY
93+
-------------------------
94+
95+
The following query collects amounts per product.
96+
97+
.. code-block:: sql
98+
99+
SELECT product, ARRAY_AGG(amount IGNORE NULLS) AS amounts
100+
FROM sales
101+
GROUP BY product
102+
103+
.. list-table::
104+
:header-rows: 1
105+
106+
* - :sql:`product`
107+
- :sql:`amounts`
108+
* - :json:`"Gadget"`
109+
- :json:`[200]`
110+
* - :json:`"Widget"`
111+
- :json:`[100, 150, 120]`
112+
113+
The ``Gadget`` group contains two rows, but the ``NULL`` amount is omitted, so its array has a single element.
114+
115+
ARRAY_AGG() versus unnesting
116+
----------------------------
117+
118+
Array aggregation can be viewed as the inverse operation of unnesting an array. The following example unnests an array literal into a stream of rows and then collects those rows back with ``ARRAY_AGG()``, reproducing the original array elements (although the order in which they come back is not guaranteed).
119+
120+
.. code-block:: sql
121+
122+
SELECT ARRAY_AGG(x) AS numbers
123+
FROM (SELECT a FROM VALUES ([2, 1, -2, 3, -2, 1, 2]) AS T(a)) AS sq,
124+
sq.a AS x
125+
126+
.. list-table::
127+
:header-rows: 1
128+
129+
* - :sql:`numbers`
130+
* - :json:`[2, 1, -2, 3, -2, 1, 2]`
131+
132+
See :ref:`Unnesting <unnesting>` for the unnesting syntax used by the inner query.
133+
134+
ARRAY_AGG() in a correlated subquery
135+
------------------------------------
136+
137+
To collect a per-parent array of related child values, use a correlated subquery in the ``FROM`` clause. For the following example, assume a ``parent`` table and a ``child`` table joined on ``pid``.
138+
139+
.. code-block:: sql
140+
141+
SELECT p.pid, sq.vals
142+
FROM parent p,
143+
(SELECT ARRAY_AGG(c.val IGNORE NULLS) AS vals FROM child c WHERE c.pid = p.pid) sq
144+
145+
A parent with no matching child rows produces a ``NULL`` array for that row.
146+
147+
.. _array-agg-important-notes:
148+
149+
Important notes
150+
===============
151+
152+
* **Required indexes**: In general, ``GROUP BY`` queries require an appropriate index to be executed. See :ref:`Indexes <index_definition>` for details on creating indexes that support ``GROUP BY`` operations.
153+
* **ARRAY_AGG() in indexes**: ``ARRAY_AGG()`` itself cannot currently be materialized in an index. Defining an index over it, as in ``CREATE INDEX idx AS SELECT ARRAY_AGG(val) FROM tab GROUP BY grp``, raises an ``UNSUPPORTED_OPERATION`` error.
154+
* **Element order**: The order of the elements within the returned array is unspecified. Elements are collected in whatever order the rows are read in, which depends on the plan use to execute the query—in particular on which index is used, if any. You therefore cannot rely on the order.
155+
* **NULL handling**: An array cannot currently hold ``NULL`` elements. This is due to a limitation at the level of the FDB Record Layer, tracked by `Issue #3646 <https://github.com/FoundationDB/fdb-record-layer/issues/3646>`_. A query that uses the default ``RESPECT NULLS`` behavior (including when no null-treatment clause is present) will fail at run time with an ``UNSUPPORTED_OPERATION`` error as soon as a ``NULL`` is encountered. To avoid this potential error, use ``IGNORE NULLS`` to omit ``NULL`` values from the array.
156+
* **Arrays of arrays**: An ``ARRAY``-typed argument would produce an array of arrays, which is not supported. ``ARRAY_AGG()`` over an ``ARRAY`` column raises an ``UNSUPPORTED_OPERATION`` error. This limitation is tracked by `Issue #4167 <https://github.com/FoundationDB/fdb-record-layer/issues/4167>`_. To collect nested collections, you can wrap the inner array in a struct, as in ``ARRAY_AGG((rid, tags))``.
157+
* **DISTINCT and ORDER BY**: These clauses are not supported yet. ``ARRAY_AGG(DISTINCT «expression» …)`` and ``ARRAY_AGG(«expression» ORDER BY …)`` both parse, but raise an ``UNSUPPORTED_QUERY`` error.
158+
* **Subqueries**: ``ARRAY_AGG()`` may be used in a correlated ``FROM``-clause subquery, as shown in `ARRAY_AGG in a correlated subquery`_ above, but not in a scalar subquery in the ``SELECT`` projection list. The latter, for example ``SELECT p.pid, (SELECT ARRAY_AGG(c.val IGNORE NULLS) FROM child c WHERE c.pid = p.pid) FROM parent p``, raises a ``SYNTAX_ERROR``. That is a general limitation of scalar subqueries in projections, not specific to ``ARRAY_AGG()``.

yaml-tests/src/test/java/DocumentationQueriesTests.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ void aggregateFunctionsDocumentationQueriesTests(YamlTest.Runner runner) throws
3434
runner.runYamsql(PREFIX + "/aggregate-functions-documentation-queries.yamsql");
3535
}
3636

37+
@TestTemplate
38+
void arrayAggDocumentationQueriesTests(YamlTest.Runner runner) throws Exception {
39+
runner.runYamsql(PREFIX + "/array-agg-documentation-queries.yamsql");
40+
}
41+
3742
@TestTemplate
3843
void betweenOperatorQueriesTests(YamlTest.Runner runner) throws Exception {
3944
runner.runYamsql(PREFIX + "/between-operator-queries.yamsql");

yaml-tests/src/test/resources/array-agg-tests.yamsql

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,7 @@ schema_template:
2828
CREATE TABLE T1 (id BIGINT, grp BIGINT, val BIGINT, PRIMARY KEY (id))
2929
CREATE INDEX T1_grp AS SELECT grp FROM T1 ORDER BY grp
3030

31-
CREATE TABLE parent (pid BIGINT, name STRING, PRIMARY KEY (pid))
32-
CREATE TABLE child (cid BIGINT, pid BIGINT, val BIGINT, PRIMARY KEY (cid))
3331
CREATE TABLE keywords (array_agg BIGINT, respect BIGINT, PRIMARY KEY (array_agg))
34-
CREATE INDEX child_by_pid AS SELECT pid FROM child ORDER BY pid
3532

3633
CREATE TYPE AS STRUCT Struct1 (a BIGINT, b BIGINT)
3734
CREATE TABLE T2 (id BIGINT, grp BIGINT, s Struct1, PRIMARY KEY (id))
@@ -57,15 +54,6 @@ setup:
5754
(6, 30, NULL)
5855
- query: INSERT INTO keywords
5956
VALUES (1, 2)
60-
- query: INSERT INTO parent
61-
VALUES (1, 'a'),
62-
(2, 'b'),
63-
(3, 'c')
64-
- query: INSERT INTO child
65-
VALUES (1, 1, 100),
66-
(2, 1, 200),
67-
(3, 2, 300),
68-
(4, 2, NULL)
6957
- query: INSERT INTO T2
7058
VALUES (1, 10, (1, 2)),
7159
(2, 10, (3, 4)),
@@ -233,21 +221,6 @@ test_block:
233221
- query: SELECT sq.agg[1] FROM (SELECT ARRAY_AGG(tags) AS agg FROM doc_rev) sq
234222
- error: UNSUPPORTED_OPERATION
235223
---
236-
test_block:
237-
name: array-agg-correlated-subquery
238-
tests:
239-
-
240-
# A correlated ARRAY_AGG() subquery in a SELECT projection is currently not supported and fails with a parse-time
241-
# syntax error. A scalar subquery is not allowed as a select-list expression (the grammar only permits EXISTS/IN
242-
# subqueries there).
243-
- query: SELECT p.pid, (SELECT ARRAY_AGG(c.val) FROM child c WHERE c.pid = p.pid) AS vals FROM parent p
244-
- error: SYNTAX_ERROR
245-
-
246-
# Supported rewrite: A correlated ARRAY_AGG() subquery in the FROM clause. This is the recommended alternative
247-
# for the projection form above. Row `pid=3` has no children, so its aggregate is NULL.
248-
- query: SELECT p.pid, sq.vals FROM parent p, (SELECT ARRAY_AGG(c.val IGNORE NULLS) AS vals FROM child c WHERE c.pid = p.pid) sq
249-
- result: [{1, [100, 200]}, {2, [300]}, {3, !null _}]
250-
---
251224
# Tests involving element types whose runtime representation differs from their protobuf one. The accumulator has to
252225
# convert such types, both when it serializes its partial state and when it hands its result to the enclosing record
253226
# constructor.
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
#
2+
# array-agg-documentation-queries.yamsql
3+
#
4+
# This source file is part of the FoundationDB open source project
5+
#
6+
# Copyright 2021-2026 Apple Inc. and the FoundationDB project authors
7+
#
8+
# Licensed under the Apache License, Version 2.0 (the "License");
9+
# you may not use this file except in compliance with the License.
10+
# You may obtain a copy of the License at
11+
#
12+
# http://www.apache.org/licenses/LICENSE-2.0
13+
#
14+
# Unless required by applicable law or agreed to in writing, software
15+
# distributed under the License is distributed on an "AS IS" BASIS,
16+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
# See the License for the specific language governing permissions and
18+
# limitations under the License.
19+
---
20+
options:
21+
supported_version: !current_version
22+
---
23+
# The `sales` table and its `product_idx` index are the ones shown in the ARRAY_AGG() documentation page. The index is
24+
# what allows the GROUP BY query below to be planned, since a streaming aggregation needs its input sorted on the
25+
# grouping column.
26+
# The `parent` and `child` tables back the “ARRAY_AGG() in a correlated subquery” section, which describes them in prose
27+
# rather than giving their DDL. The `doc_rev` table backs the “Arrays of arrays” note, whose examples use `rid` and
28+
# `tags`.
29+
schema_template:
30+
CREATE TABLE sales (id BIGINT, product STRING, region STRING, amount BIGINT, PRIMARY KEY (id))
31+
CREATE INDEX product_idx AS SELECT product FROM sales ORDER BY product
32+
33+
CREATE TABLE parent (pid BIGINT, name STRING, PRIMARY KEY (pid))
34+
CREATE TABLE child (cid BIGINT, pid BIGINT, val BIGINT, PRIMARY KEY (cid))
35+
CREATE INDEX child_by_pid AS SELECT pid FROM child ORDER BY pid
36+
37+
CREATE TABLE doc_rev (rid BIGINT, title STRING, tags STRING ARRAY, PRIMARY KEY (rid))
38+
---
39+
setup:
40+
steps:
41+
- query: INSERT INTO sales VALUES
42+
(1, 'Widget', 'North', 100),
43+
(2, 'Widget', 'South', 150),
44+
(3, 'Gadget', 'North', 200),
45+
(4, 'Gadget', 'South', NULL),
46+
(5, 'Widget', 'North', 120)
47+
- query: INSERT INTO parent VALUES (1, 'a'), (2, 'b'), (3, 'c')
48+
- query: INSERT INTO child VALUES (1, 1, 100), (2, 1, 200), (3, 2, 300), (4, 2, NULL)
49+
- query: INSERT INTO doc_rev VALUES (10, 'draft', ['internal']), (20, 'final', ['featured', 'public'])
50+
---
51+
test_block:
52+
name: array-agg-documentation-tests
53+
preset: single_repetition_ordered
54+
tests:
55+
-
56+
- query: SELECT ARRAY_AGG(amount IGNORE NULLS) AS amounts FROM sales
57+
- result: [{amounts: [200, 100, 150, 120]}]
58+
59+
-
60+
- query: SELECT product, ARRAY_AGG(amount IGNORE NULLS) AS amounts
61+
FROM sales
62+
GROUP BY product
63+
- result: [{product: 'Gadget', amounts: [200]},
64+
{product: 'Widget', amounts: [100, 150, 120]}]
65+
66+
-
67+
- query: SELECT ARRAY_AGG(x) AS numbers
68+
FROM (SELECT a FROM VALUES ([2, 1, -2, 3, -2, 1, 2]) AS T(a)) AS sq,
69+
sq.a AS x
70+
- result: [{numbers: [2, 1, -2, 3, -2, 1, 2]}]
71+
72+
-
73+
- query: SELECT p.pid, sq.vals
74+
FROM parent p,
75+
(SELECT ARRAY_AGG(c.val IGNORE NULLS) AS vals FROM child c WHERE c.pid = p.pid) sq
76+
- result: [{pid: 1, vals: [100, 200]},
77+
{pid: 2, vals: [300]},
78+
{pid: 3, vals: !null _}]
79+
80+
-
81+
- query: SELECT p.pid, (SELECT ARRAY_AGG(c.val IGNORE NULLS) FROM child c WHERE c.pid = p.pid) FROM parent p
82+
- error: SYNTAX_ERROR
83+
84+
-
85+
# “Arrays of arrays”: Aggregating an ARRAY-typed argument is rejected, …
86+
- query: SELECT ARRAY_AGG(tags) FROM doc_rev
87+
- error: UNSUPPORTED_OPERATION
88+
89+
-
90+
# … while wrapping the inner array in a struct works.
91+
- query: SELECT ARRAY_AGG((rid, tags)) FROM doc_rev
92+
- result: [{[{10, ['internal']}, {20, ['featured', 'public']}]}]
93+
94+
---
95+
# “ARRAY_AGG() in indexes”: An index cannot be defined over ARRAY_AGG(). The schema template is created against the catalog,
96+
# as it is the DDL itself that has to be rejected.
97+
test_block:
98+
name: array-agg-not-indexable-documentation-tests
99+
connect: "jdbc:embed:/__SYS?schema=CATALOG"
100+
preset: single_repetition_ordered
101+
tests:
102+
-
103+
- query: CREATE SCHEMA TEMPLATE array_agg_doc_index_template
104+
CREATE TABLE tab(id BIGINT, grp BIGINT, val BIGINT, PRIMARY KEY(id))
105+
CREATE INDEX idx AS SELECT ARRAY_AGG(val) FROM tab GROUP BY grp
106+
- error: UNSUPPORTED_OPERATION
107+
...

0 commit comments

Comments
 (0)