Add primary key constraints and create auto-increment sequences when oracle creates tables

1. About the primary key: specify the primary key when creating the table:
create table test(
  id number(6) primary key,
  name varchar2(30)
);
if you want to add a primary key constraint for an already built table, then Similar syntax:
alter table test add constraint pk_id primary key(id); 
where add constraint and primary key are keywords, and pk_id is the name of the primary key, which can be customized as long as it is not repeated.

2. Regarding the id auto-increment function, it is also very simple and flexible .
(1) First create a sequence (that is, a non-repeating object that will automatically increase the value each time you query , such as adding 1 each time or adding 10 each time). Syntax:
CREATE SEQUENCE sequence name
[INCREMENT BY n] -- add a few each time
[ START WITH n] -- the sequence starts from a few [{MAXVALUE/ MINVALUE n|NOMAXVALUE}] -- the minimum and maximum limit such as CREATE SEQUENCE s_test start with

1 increment by 1; -- is to establish a sequence that starts from 1 and increments by 1 each time.
When accessing a sequence, use the syntax of sequencename.nextval .

For example, for the above table, if you want the id field to be auto-incremented. Then every time you insert a record , use a syntax similar to the following (provided that the table and sequence have been built).
insert into test values ​​(s_test.nextval, 'Zhang San');

Of course, you can also automatically, create a trigger for the insertion operation of the table. Whenever data is inserted, the trigger automatically modifies the id value of the sequence new value, so that the auto-increment id function is fully realized. But it's not really necessary. Because if there are too many triggers, it will sometimes be confusing and difficult to manage.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324854805&siteId=291194637