Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create the aggregate if not exists

Tags:

postgresql

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?

like image 288
StellaMaris Avatar asked Jun 02 '16 22:06

StellaMaris


People also ask

How do you create an aggregate?

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.

Can we use aggregate function without group by?

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.

Is not an aggregate function in SQL?

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.

Can PostgreSQL users create their own aggregate functions?

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.


2 Answers

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

like image 149
Nick Avatar answered Sep 30 '22 09:09

Nick


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.

like image 30
ldav1s Avatar answered Sep 30 '22 09:09

ldav1s