English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PostgreSQL AUTO INCREMENT (Auto Increment)

AUTO INCREMENT (auto-increment) generates a unique number when a new record is inserted into the table.

PostgreSQL uses sequences to identify the auto-incrementing fields, with data types smallserial, serial, and bigserial. These attributes are similar to the AUTO_INCREMENT attribute supported by MySQL databases.

The statement to set automatic increment in MySQL is as follows:

CREATE TABLE IF NOT EXISTS `w3codebox_tbl(
   `w3codebox_id INT UNSIGNED AUTO_INCREMENT,
   `w3codebox_title VARCHAR(100) NOT NULL,
   `w3codebox_author VARCHAR(40) NOT NULL,
   `submission_date` DATE,
   PRIMARY KEY (3codebox_id
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

MySQL uses the AUTO_INCREMENT attribute to identify the auto-incrementing fields.

PostgreSQL uses sequences to identify the auto-incrementing fields:

CREATE TABLE w3codebox
(
    id serial NOT NULL,
    alttext text,
    imgurl text
)

SMALLSERIAL, SERIAL and BIGSERIAL Range:

Pseudo-TypeStorage SizeRange
SMALLSERIAL2bytes1 to 32,767
SERIAL4bytes1 to 2,147,483,647
BIGSERIAL8bytes1 to 922,337,2036,854,775,807

Syntax

SERIAL  data type basic syntax is as follows:

CREATE TABLE tablename (
   colname SERIAL
);

Online Example

Assuming we want to create a COMPANY table and create the following fields:

w3codeboxdb=# CREATE TABLE COMPANY(
   ID  SERIAL PRIMARY KEY,
   NAME           TEXT      NOT NULL,
   AGE            INT       NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

Now insert several records into the table:

INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Paul', 32, 'California', 20000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Allen', 25, 'Texas', 15000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ('Teddy', 23, 'Norway', 20000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Mark', 25, 'Rich-Mond ', 65000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'David', 27, 'Texas', 85000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'Kim', 22, 'South-Hall', 45000.00 );
INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'James', 24, 'Houston', 10000.00 );

View the records of the COMPANY table as follows:

 id | name  | age | address    | salary
----+-------+-----+------------+--------
  1 | Paul  |  32 | California |  20000
  2 | Allen |  25 | Texas      |  15000
  3 | Teddy |  23 | Norway     |  20000
  4 | Mark  |  25 | Rich-Mond  |  65000
  5 | David |  27 | Texas      |  85000
  6 | Kim   |  22 | South-Hall |  45000
  7 | James |  24 | Houston    |  10000