Trong PostgreSQL, khi tạo bảng CSDL chúng ta sử dụng SERIAL để định nghĩa 1 auto-increment column – column có ID (integer) tự động tăng.
Khi column được định nghĩa là SERIAL, PostgreSQL sẽ tạo ra 1 column với kiểu dữ liệu Integer và tạo ra 1 sequence cho column đó. Sequece là 1 đối tượng dữ liệu của kiểu dữ liệu Integer tự động tăng trong PostgreSQL.
Các loại SERIAL Datatype trong PostgreSQL
| Name | Storage Size | Range | 
| SMALLSERIAL | 2 bytes | 1 to 32,767 | 
| SERIAL | 4 bytes | 1 to 2,147,483,647 | 
| BIGSERIAL | 8 bytes | 1 to 9,223,372,036,854,775,807 | 
Tạo Auto-Increment Column sử dụng SERIAL
Cú pháp lệnh:
CREATE TABLE table_name( id SERIAL );
Ví dụ: Tạo bảng groups với trường group_id là auto-increment column
CREATE TABLE groups
(
    group_id SERIAL,
    group_name character varying COLLATE pg_catalog."default" NOT NULL,
    created_at timestamp without time zone NOT NULL,
    updated_at timestamp without time zone,
    deleted_at timestamp without time zone,
    CONSTRAINT groups_pkey PRIMARY KEY (group_id)
)
Kết quả:
Chúng ta tạo được 1 sequece có tên là: groups_group_id_seq và nó được gán vào column group_id của bảng groups

Để kiếm tra lại, thử insert dữ liệu vào bảng groups bằng câu SQL sau:
INSERT INTO groups(group_name, created_at) VALUES('staff', '2019-09-12 00:00:00');
INSERT INTO groups(group_name, created_at) VALUES('sale', '2019-09-13 00:00:00');
INSERT INTO groups(group_name, created_at) VALUES('admin', '2019-09-14 00:00:00');
Kết quả:
