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
identityorserialcolumnserialand how to fix that numbers are not continuous.