Example tutorial of creating auto increment primary key in Oracle Database

Time:2020-11-20

When designing the database table, we found that Oracle does not have the setting of auto increment primary key. Google understands that Oracle itself does not support auto increment primary key, which needs to be implemented through sequence and trigger.
Create table student

Create Table Student( 
 ID number (12) primary key, -- self increment of ID through sequence and trigger 
 name varchar2(20) , 
 age number(3) , 
 sex number(1) 
)

Create sequence

Create Sequence SEQ_STUDENT 
minvalue 1 
maxvalue 99999999999999999999 
Start with 1 -- start with 1 
Increment by 1 -- increment by 1 
cache 0 
order;

Create trigger trigger


Create or Replace Trigger STUDENT_AUTOINCREMENT 
Before Insert on Student 
For Each Row 
When (NEW.ID IS NULL) 
Begin 
Select SEQ_STUDENT.NEXTVAL INTO :NEW.ID FROM DUAL; 
End; 

Note:

1: A sequence can be shared by multiple tables.

2: The sequence generated by a sequence shared by multiple tables is always continuous and does not restart.

3: If you no longer use the sequence, delete it.


SELECT * FROM DAYSBFJ.DAYS_CARD_UPDATE3 order by id asc
--alter table DAYSBFJ.DAYS_CARD_UPDATE3 add source_Flag varchar2(2);
--create sequence DAYS_CARD_UPDATE2_SEQ_ID minvalue 1 maxvalue 999999999 start with 1;
--Update DAYSBFJ.DAYS_CARD_UPDATE2 set id = DAYS_CARD_UPDATE2_SEQ_ID.nextval;
--update DAYSBFJ.DAYS_CARD_UPDATE3 set SOURCE_FLAG = '2'

Another example:

Create a new table without a primary key


create table test1(name1 varchar2(40),city varchar2(40));

–Insert data


insert into test1 values('name1','nanjing');
insert into test1 values('name1','nanjing');
insert into test1 values('name2','nanjing1');
insert into test1 values('name3','nanjing2');
insert into test1 values('name4','nanjing3');
insert into test1 values('name5','nanjing4');
insert into test1 values('name6','nanjing5');
insert into test1 values('name7','nanjing6');
insert into test1 values('name8','nanjing7');
insert into test1 values('name9','nanjing8');
insert into test1 values('name10','nanjing9');
insert into test1 values('name10','nanjing9');
insert into test1 values('name12','nanjing11');
insert into test1 values('name13','nanjing12');
insert into test1 values('name14','nanjing13');
commit;

–Add primary key ID


alter table TEST1 add id number(10);

–Set sequence to increase ID automatically


create sequence SEQ_ID
 minvalue 1
 maxvalue 999999999
 start with 1;

–Set the value of ID to sequence


Update test1 set id=seq_id.nextval;
commit;

–Set ID as primary key


alter table TEST1
 add constraint PK_TEST1 primary key (ID);
 
select ID,Name1,CITY from TEST1;