Skip to Main Content

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Geraldo.

Asked: October 17, 2018 - 12:14 pm UTC

Last updated: October 17, 2018 - 1:33 pm UTC

Version: 12.2.0

Viewed 1000+ times

You Asked

Hello.

I'm designing a database in Oracle 12.2 in Toad Data Modeler. It would get lots of inserts.

I'm using identity columns as PK (basically I create a sequence and use it as default value in the column, sequence.nextval). When I connect the PK column in parent table to the child table the new FK column comes with sequence.nextval as default value.

1. Is this the expected behavior? or should I user sequence.currval as default value?

2. Should I let the app handle the value in the FK on the child table? If so, is it OK to let sequence.nextval as default value in FK because it is ignored when a value comes in the insert statement?

3. What would be the best aproach?

Thanks in advance.

Regards,

and Chris said...

1. No. Only use the seq.nextval for the parent's primary key. Trying to use the sequence on the child's FK column will cause bugs. Anyone could call seq.nextval between the parent insert and the child. So you could insert for the wrong parent!

2. If by app, you mean your code, then yes. Do NOT use seq.nextval for the child's FK column.

3. Use the returning clause of insert to capture the new PK value. Then use that in your child inserts:

create sequence s;
create table t1 (
  c1 int default s.nextval primary key
);

create table t2 (
  t1_c1 int 
    references t1 ( c1 ) 
);

declare
  t1id int;
begin
  
  insert into t1 values ( default )
  returning c1 into t1id;
  
  insert into t2 values ( t1id );
  
end;
/

select * from t1;

C1   
   1 

select * from t2;

T1_C1   
      1 

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Excellent

Geraldo Peralta, October 17, 2018 - 7:05 pm UTC

Excellent!

Thanks for the answer.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.