Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is ARRAY_AGG() guaranteed to be stable (i.e. do the resulting elements show up in the same order as the input)?

From my testing, ARRAY_AGG() appears to be stable in the sense that it doesn’t reorder the input data. For example,

SELECT ARRAY_AGG(x) AS array_agg FROM UNNEST([20, 40, 50, 1, 2, 3]) AS x;

+-------------------------+
| array_agg               |
+-------------------------+
| [20, 40, 50, 1, 2, 3]   |
+-------------------------+

Notice the order of those elements is unchanged. Is this behavior guaranteed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

These things tend to be stable, but the order is not guaranteed.

From Aggregate function calls:

The ORDER BY clause is supported only for aggregate functions that depend on the order of their input. For those functions, if the ORDER BY clause is omitted, the output is nondeterministic.

It’s best to specify the order explicitly, for example:

ARRAY_AGG(x ORDER BY ABS(x))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading