Skip to content
Advertisement

Writing my own aggregate function in postgresql

I’ve never wriiten my own aggreagtes, only store procedures and I need some advice. I want to write a custom aggregate which is going to return maximum value of the integer rows and incerement it by 10. How can I do that? I tried this:

but it didn’t work. Can someone help me out?

I got the error:

Honestly, I didn’t understand how it should work.

Advertisement

Answer

The following example shows how to create an aggregate using custom functions:

Sfunc is a state transition function. It is executed in an aggregation as many times as there are rows to aggregate. Its first argument is an internal-state, i.e. the value accumulated so far. In the first call the value is equal to initcond (or null if initcond was not defined). The second argument is a next-data-value, i.e. value from the next row. In the above example the function calculates the maximum of not null positive integers and is executed four times (for four rows):

Finalfunc is executed once at the end of an aggregation. It has one argument (the value calculated so far) and returns the final (modified) result of the aggregation. In our example it just adds 10 to the result of the aggregation.

Read more in the documentation.

The example above is just a kind of exercise. In fact, there is no need to define such an aggregate since select max (v + 10) gives the desired result.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement