Execute a Custom Function In Each Record Returned By the SELECT Query #8
vbilopav
started this conversation in
PostgreSQL
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Execute a custom function in each record returned by the SELECT query
Start with a query that returns a series of numbers:
select q.i from generate_series(1, 10) q(i)
The goal is to execute a custom function for each record in this select (this is just an example; query could be anything).
That something will always return a previous value for the field
i
in theq(i)
test table.That is essentially a custom implementation of the LAG window function, but this serves as a proof of concept to demonstrate that we can do a custom function call for each value in any SELECT.
We will do this in a function that
test_rec()
that returns table (i, j), wherei
is a value fromgenerate_series
andj
is the result from a custom function executed for each result that represents a previous (lag) value.First, we need a wrap-up that generate-series in a subquery because
generate_series
returns a number, not a table record, and we need a table record:test_rec()
, we will create a new function that will do this custom processing. This function will receive entire record and return the result of the previous (lag) calculation.pg_temp
schema. That means it is visible only to the current connection (session), and it will be dropped when the connection (session) ends. Alternatively, this function could be global at any schema.plpgsql
function because plainsql
function can't work with therecord
type, and we have a parameter which is generic (any) table record_rec record
.test_rec.prev
. Unscoped names are usually reserved for the system.::int
2) we to checknullif
to set to null empty strings.record
type inplpgsql
and how it can be used to process records with custom logic.The last two concepts assume that there will be no parallel calls on the same connection which is the bad practice anyway (if it is even possible).
And now, we can call this:
Beta Was this translation helpful? Give feedback.
All reactions