0

How to set a default value to the maximum value of the field + 1.

I tried:

,no_af          integer UNIQUE NOT NULL DEFAULT max(no_af)+1

but got the answer :

"ERROR: ERREUR: les fonctions d'agrégats ne sont pas autorisés dans les expressions par défaut"

4
  • you just need to set it to auto incremental Commented Nov 18, 2020 at 14:50
  • Do not do that. Use an identity or serial column Commented Nov 18, 2020 at 14:56
  • @Laurenz Albe No but this number si used to reference the job internally. Commented Nov 20, 2020 at 7:10
  • Using serial and how to fix that numbers are not continuous. Commented Dec 29, 2022 at 3:28

3 Answers 3

1

I'm glad for you that it didn't work. Please please don't do that. Use a sequence instead:

,no_af serial UNIQUE NOT NULL

If your design requires no holes in the sequence of values, then replace the design with one that allows holes.

Sign up to request clarification or add additional context in comments.

2 Comments

That's the problem, I can't allow holes.. The value is a number that represent the annual number of case we work on.
But there is no need to store that annual count as an automatically generated number in the database. You can easily find out the number of cases for a year with a query.
0

I found a way using a trigger:

CREATE FUNCTION no_af_incrementation() RETURNS trigger AS $no_af_incrementation$
begin
    if NEW.no_af is NULL then
        NEW.no_af := (select max(no_af)+1 from af.od_af);
    end if;
    return NEW;
end;

3 Comments

This is not going to work correctly if you have concurrent transactions inserting into that table. And how are you going to prevent holes if you allow the value to be specified in an INSERT statement?
If you truly need a gapless increasing number, consider something like this
@a_horse_with_no_name The link you posted works perfectly, thanks
0

Create a FUNCTION and use it in the DEFAULT defination.

CREATE OR REPLACE FUNCTION "public"."table_next_id"("table" text)
  RETURNS "pg_catalog"."int4" AS $BODY$
    DECLARE
    next_id int4 = 0;
    BEGIN
        EXECUTE format('select max(id)+1 from %s', "table") INTO next_id;       
    RETURN COALESCE(next_id, 1);
END$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
CREATE TABLE "public"."merchant" (
  "id" int4 NOT NULL DEFAULT table_next_id('merchant'::text),
  "num" int4 NOT NULL,
  CONSTRAINT "merchant_pkey" PRIMARY KEY ("id")
);

I don't know if are there potential problems, especially in concurrent insertes. But it does work.

pg version 15.1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.