Home > Database > Mysql Tutorial > How Can I Efficiently Combine Arrays into Multi-Dimensional Arrays in PostgreSQL?

How Can I Efficiently Combine Arrays into Multi-Dimensional Arrays in PostgreSQL?

Barbara Streisand
Release: 2025-01-06 01:11:39
Original
751 people have browsed it

How Can I Efficiently Combine Arrays into Multi-Dimensional Arrays in PostgreSQL?

Combining Arrays into Multi-Dimensional Arrays in PostgreSQL

Introduction

PostgreSQL provides various options for combining arrays efficiently, making it possible to manipulate complex data structures with ease.

Simple zip() Function (Same Length Arrays)

To combine two arrays of equal length, you can utilize the unnest() function along with the ARRAY[] constructor:

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() Function Aggregating to Multi-Dimensional Arrays

For aggregating paired elements into a multi-dimensional array, PostgreSQL offers the custom aggregate function array_agg_mult():

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

Usage:

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
Copy after login

Alternatively, the zip2() function can be created as a wrapper around array_agg_mult():

CREATE OR REPLACE FUNCTION zip2(anyarray, anyarray)
RETURNS SETOF anyarray LANGUAGE SQL AS
$func$
SELECT array_agg_mult(ARRAY[ARRAY[a,b]])
FROM (SELECT unnest() AS a, unnest() AS b) x;
$func$
Copy after login

Usage:

SELECT zip2('{a,b,c}'::text[], '{d,e,f}'::text[]);
Copy after login

Result:

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

Postgres 9.5 (array_agg(array expression))

In Postgres 9.5 and later, the array_agg(array expression) function can directly combine arrays into a multi-dimensional array, providing a more efficient solution compared to the custom aggregate function. Its usage is similar to the array_agg_mult() function.

The above is the detailed content of How Can I Efficiently Combine Arrays into Multi-Dimensional Arrays in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

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