Home > Database > Mysql Tutorial > How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?

How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?

Linda Hamilton
Release: 2025-01-04 18:28:40
Original
519 people have browsed it

How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?

Postgres: Combining Two Arrays Using a "zip()" Function

Postgres Functions

There are several methods to combine two arrays into a single multidimensional array using Postgres functions:

Postgres 9.5 or later:

  • array_agg(array expression): Concatenates all input arrays into an array of one higher dimension.

Postgres 9.4:

  • ROWS FROM or unnest(): Unnests multiple arrays in parallel, allowing arrays of different lengths.

Postgres 9.3 or older:

  • zip(): A custom function that unnests two arrays simultaneously, creating a new set of arrays.

Simple zip() Function

Consider the following example for Postgres 9.3 or earlier:

SELECT ARRAY[a,b] AS ab
FROM  (
   SELECT unnest('{a,b,c}'::text[]) AS a
        , unnest('{d,e,f}'::text[]) AS b
    ) x;
Copy after login

Result:

  ab
-------
 {a,d}
 {b,e}
 {c,f}
Copy after login

zip() to Multi-Dimensional Array

To aggregate the resulting set of arrays into a 2-dimensional array, a custom aggregate function called array_agg_mult() is needed:

CREATE AGGREGATE array_agg_mult (anyarray) (
   SFUNC    = array_cat
 , STYPE    = anyarray
 , INITCOND = '{}'
);
Copy after login

Then, use it as follows:

SELECT array_agg_mult(ARRAY[ARRAY[a,b]]) AS ab
FROM  (
   SELECT unnest('{a,b,c}'::text[]) AS a
        , unnest('{d,e,f}'::text[]) AS b
    ) x;
Copy after login

Result:

{{a,d},{b,e},{c,f}}
Copy after login

The above is the detailed content of How to Zip Two Arrays in PostgreSQL to Create a Multi-Dimensional Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template