1

I am migrating Oracle DLL to PostgreSQL, I am having an issue translate the following piece of code to PostgreSQL

-- Generate ID using sequence and trigger
CREATE SEQUENCE partner_seq START WITH 1 INCREMENT BY 1;

CREATE OR REPLACE TRIGGER partner_seq_tr
 BEFORE INSERT ON partner FOR EACH ROW
 WHEN (NEW.idPartner IS NULL)
BEGIN
 SELECT partner_seq.NEXTVAL INTO :NEW.idPartner FROM DUAL;
END;
/
-- CREATE UNIQUE INDEX partner_idxName ON partner (Name);
-- COMMIT; 
3
  • Are you trying to have a idPartner have a sequence attached to it? If so how about setting the DEFAULT value for idPartner to nextval('partner_seq')? Commented Aug 6, 2020 at 2:53
  • Hello Maria did you look ora2pg utility ? ora2pg.darold.net Else ... From what I understand, you want to create a column in auto increment. It is precisely a native implementation under PostgreSQL .... Maybe this could help: postgresqltutorial.com/postgresql-serial Have fun Commented Aug 6, 2020 at 2:54
  • No, interesting I take a look Commented Aug 6, 2020 at 2:56

1 Answer 1

4

You don't actually need a trigger in Postgres for that. Simply declare the column as

idpartner integer generated always as identity

And Postgres will use the (automatically created) sequence automatically if the column is not specified as a target column in the INSERT statement.

Alternatively, if you really want a trigger:

create sequence partner_seq;

create function assign_partner_id()
  returns trigger
as
$$
begin 
  if new.idpartner is null then 
     new.idpartner := nextval('partner_seq');
  end if;
  return new;
end;
$$
language plpgsql;

create trigger partner_seq_trg
  before on partner insert on each row
  execute procedure assign_partner_id();
Sign up to request clarification or add additional context in comments.

2 Comments

I am working with spring boot app,that's why i need to created triggers .. constantly getting ERROR: relation "hibernate_sequence" does not exist. Adding trigger as you suggested has a syntax error at -------- insert on each row ERROR: syntax error at or near "row"
The joys of obfuscation layers... Regarding the syntax error: see my edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.