Home > Database > Mysql Tutorial > How Can I Efficiently Call a Set-Returning Function with an Array Argument Multiple Times in PostgreSQL?

How Can I Efficiently Call a Set-Returning Function with an Array Argument Multiple Times in PostgreSQL?

Linda Hamilton
Release: 2024-12-26 12:32:10
Original
893 people have browsed it

How Can I Efficiently Call a Set-Returning Function with an Array Argument Multiple Times in PostgreSQL?

Calling a Set-Returning Function with an Array Argument Multiple Times

This discussion centers around a set-returning function named foo that can process an array of data utilizing a specific parameter and provides a result containing a set of rows and an additional column. While the function operates successfully with a single data set, it encounters challenges when attempting to process multiple data sets without relying on a data ID for referencing.

Various attempts to modify the syntax, such as utilizing the following format:

SELECT dataid, (foo(ARRAY_AGG(data)),1).*
FROM dataset
WHERE dataid = something -- only testing on 1
GROUP BY dataid
Copy after login

have been unsuccessful, resulting in the function being called repeatedly for each column.

Solution: Lateral Join

In PostgreSQL versions 9.3 and beyond, using a LEFT JOIN LATERAL construct typically yields optimal results:

SELECT sub.dataid, f.*
FROM (
   SELECT dataid, array_agg(data) AS arr
   FROM dataset
   WHERE dataid = something
   GROUP BY 1
   ) sub
LEFT JOIN LATERAL foo(sub.arr) f ON true;
Copy after login

This syntax ensures that all rows to the left of the join are preserved, even if the function foo returns no rows.

If foo can indeed return no rows and excluding those rows is desired, the following syntax can be employed:

CROSS JOIN LATERAL foo(sub.arr)
Copy after login

or its shorthand version:

, foo(sub.arr)
Copy after login

This approach is documented in the PostgreSQL manual.

The above is the detailed content of How Can I Efficiently Call a Set-Returning Function with an Array Argument Multiple Times in PostgreSQL?. 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