in my sql script I want to return with the last query some records. For that query I'm using a aggregate:
CREATE AGGREGATE array_agg_mult(anyarray) (
SFUNC = array_cat,
STYPE = anyarray,
INITCOND = '{}'
);
So if I call the script twice I have to drop the aggregate at the end. But the script should end with a custom sql query. Is there a way to say something like CREATE OR REPLACE
?
To be able to create an aggregate function, you must have USAGE privilege on the argument types, the state type(s), and the return type, as well as EXECUTE privilege on the supporting functions.
While all aggregate functions could be used without the GROUP BY clause, the whole point is to use the GROUP BY clause. That clause serves as the place where you'll define the condition on how to create a group. When the group is created, you'll calculate aggregated values.
Which of the following is not a built in aggregate function in SQL? Explanation: SQL does not include total as a built in aggregate function. The avg is used to find average, max is used to find the maximum and the count is used to count the number of values.
Fortunately, PostgreSQL is really flexible and allows end users to create your own aggregation functions, which can help to move your business logic to PostgreSQL. The “CREATE AGGREGATE” command is there to create all kinds of aggregations.
You could simply DROP AGGREGATE IF EXISTS array_agg_mult(anyarray);
prior to your CREATE AGGREGATE
Note that this may throw an error if you change the parameters/signature, so you'd need to adjust for that if you do.
Manual Reference: https://www.postgresql.org/docs/current/static/sql-dropaggregate.html
DO $$ BEGIN
CREATE AGGREGATE array_agg_mult(anyarray) (
SFUNC = array_cat,
STYPE = anyarray,
INITCOND = '{}'
);
EXCEPTION
WHEN duplicate_function THEN NULL;
END $$;
seems to work as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With