Oracle adds a primary key to the table and makes the ID self-increment

Source: Internet
Author: User

1, about the primary key: the construction of the table when the specified primary key words can:
CREATE TABLE Test (
ID Number (6) primary key,
Name VARCHAR2 (30)
);
If you want to increase the primary KEY constraint for a table that has already been built, you would like the syntax:
ALTER TABLE TEST add constraint pk_id primary key (ID);
Where add constraint and primary key are keywords, pk_id is the primary key name, custom amount, as long as you do not repeat.

2, about the ID self-increment function, is also very simple, and more flexible.
(1) First set up a sequence (that is, each time the query will automatically increment the value of the never-repeated object, such as 1 or each time plus 10). Grammar:
CREATE Sequence sequence Name
[INCREMENT by N]--Each time you add a few
[Start with n]-sequence from several beginnings
[{Maxvalue/minvalue n| Nomaxvalue}]--limit of minimum and maximum value
Like whatCREATE sequence s_test start with 1 increment by 1;--that is, a sequence that starts from 1 and adds 1 each time.
When you access a sequence, use the sequence name. Nextval syntax.

For example, for the table above, if you want the ID field to implement self-increment. Each time you insert a record, use a syntax similar to the following (provided the table and sequence are already built).
INSERT into test values (S_test.nextval, ' Zhang San ');

Of course, you can also automatically, to insert operations on the table, to create a trigger, whenever there is data inserted, the trigger automatically modifies the ID value to the new value of the sequence, so that the self-increment ID function is fully implemented. But there is no need for that. Because if the trigger is built more, it is sometimes confusing and difficult to manage.

Oracle adds a primary key to the table and makes the ID self-increment

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.