PostgreSQL auto increment primary key creation method

Source: Internet
Author: User
Tags postgresql

In postresql, you only need to set the field type to serial.

For example

The code is as follows: Copy code

Create table st_cat
(
Id serial not null,
Parentid integer,-parent id
Catname character varying (20),-category name
Memo character varying (500),-remarks
Issub integer-whether subcategory exists
)
WITH (
OIDS = FALSE
);
Alter table st_cat
Owner to IPVs;
Comment on column st_cat.parentid IS 'parent ID ';
Comment on column st_cat.catname IS 'Category name ';
Comment on column st_cat.memo IS 'note ';
Comment on column st_cat.issub IS 'has subcategory ';


It's strange to see similar code on the Internet.

The code is as follows: Copy code

Nextval ('test _ a_id_seq ': regclass)

Where did this come from,

Later I found it in pgAdmin. It is in the corresponding table field and will appear

The code is as follows: Copy code

Alter table test_a add column id integer;
Alter table test_a alter column id set not null;
Alter table test_a alter column id set default nextval ('test _ a_id_seq ': regclass );

Use the last one.

In this way, you can insert data as you like.

In Java code, sqlSession. commit (); operations are indispensable, otherwise the results will not be seen.

You can also use the oid field of each row as a unique value. However, if you need to dump or reload the database, you need to use the-o option of pg_dump or the copy with oids option to retain the OID.

The code is as follows: Copy code

Insert into person values (nextval ('person _ id_req '), 'yourname ');

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.