开发者

What is the acceptable method for generating an auto incrementing primary key in PostgreSQL?

Is there no easy way to do this without sequences and 开发者_开发知识库triggers? I have average SQL skills, and I want to use the industry standard method for pl/sql (PostgreSQL). I'm basically converting over this example table from Spring Security:

create table group_members (
    id bigint generated by default as identity(start with 0) primary key,
    username varchar(50) not null,
    group_id bigint not null,
    constraint fk_group_members_group foreign key(group_id) references groups(id));

What I have so far:

CREATE TABLE auth_group_members (
    id NUMBER,
    username VARCHAR(50) NOT NULL,
    group_id NUMBER NOT NULL,
    CONSTRAINT "FK_AuthGroupMembers" FOREIGN KEY(group_id) REFERENCES auth_groups(id)
);


The standard way would be to use serial or bigserial:

The data types serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).
[...]
Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator.

So you'd create the table with something like this:

CREATE TABLE auth_group_members (
    id bigserial primary key,
    username VARCHAR(50) NOT NULL,
    group_id NUMBER NOT NULL,
    CONSTRAINT "FK_AuthGroupMembers" FOREIGN KEY(group_id) REFERENCES auth_groups(id)
);

The serial and bigserial types do create a sequences behind the scenes but you never have to work with the sequence directly.


In PostgreSQL 10 you can use identity columns. Here is example:

create table group_members (
    id bigint generated by default as identity(start with 1) primary key,
    username varchar(50) not null,
    group_id bigint not null
    );

Additionally:

  1. Good article about identity columns vs serial.
  2. PostgreSQL documentation for more info (Ctrl+F and search "AS IDENTITY").
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜