Search code examples
postgresqlsql-updateauto-increment

PostgreSQL increment serial column on update


I am trying to increment a serial column after an update. I have written a trigger function to help.

    CREATE FUNCTION "public"."update_transaction_id" () RETURNS trigger AS
$BODY$
    DECLARE
        curr_id integer;
    BEGIN
        curr_id = nextval(pg_get_serial_sequence('current_table', 'transaction_id'));
        NEW.transaction_id = curr_id;
        PERFORM SETVAL((SELECT pg_get_serial_sequence('current_table', 'transaction_id')), curr_id + 1, false);
        RETURN NEW;
    END; 
$BODY$ LANGUAGE 'plpgsql' IMMUTABLE CALLED ON NULL INPUT SECURITY INVOKER;

CREATE TRIGGER "trg_update_transaction_id" AFTER UPDATE
    ON "current_table" FOR EACH ROW
    EXECUTE PROCEDURE "public"."update_transaction_id"();

So the column is transaction_id in the table current_table. The query executes fine and the my update function does run through this trigger. However, the transaction_id column remains the same value. Is there something wrong with this procedure?


Solution

  • There are three errors in your code. First, you use the equality operator = instead of the assignment operator :=. Second, you should not SETVAL the sequence; it knows perfectly well how to maintain itself. Third, this function should be called by a BEFORE UPDATE trigger or the assignment to transaction_id will not persist.

    So why not simply:

    CREATE FUNCTION update_transaction_id() RETURNS trigger AS $BODY$
    BEGIN
      NEW.transaction_id := nextval('seq_name');
      RETURN NEW;
    END; 
    $BODY$ LANGUAGE 'plpgsql';
    

    You can trivially retrieve the immutable name of the sequence from the table definition, so plug that in straightaway.