Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PostgreSQL AUTO INCREMENT (Auto Increment)

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 auto-incrementing fields; the data types are smallserial, serial, and bigserial. These are similar to the AUTO_INCREMENT attribute supported by MySQL databases.

The statement to set auto-increment in MySQL is as follows:



CREATE TABLE IF NOT EXISTS `runoob_tbl`(

   `runoob_id` INT UNSIGNED AUTO_INCREMENT,

   `runoob_title` VARCHAR(100) NOT NULL,

   `runoob_author` VARCHAR(40) NOT NULL,

   `submission_date` DATE,

   PRIMARY KEY ( `runoob_id` )

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

MySQL uses the AUTO_INCREMENT attribute to identify a field's auto-increment.

PostgreSQL uses sequences to identify a field's auto-increment:

CREATE TABLE runoob

(

    id serial NOT NULL,

    alttext text,

    imgurl text

)

Ranges of SMALLSERIAL, SERIAL, and BIGSERIAL:

Pseudo-type Storage size Range
SMALLSERIAL 2 bytes 1 to 32,767
SERIAL 4 bytes 1 to 2,147,483,647
BIGSERIAL 8 bytes 1 to 922,337,2036,854,775,807

Syntax

The basic syntax of the SERIAL data type is as follows:

CREATE TABLE tablename (

   colname SERIAL

);

Example

Suppose we want to create a COMPANY table with the following fields:

runoobdb=# CREATE TABLE COMPANY(

   ID  SERIAL PRIMARY KEY,

   NAME           TEXT      NOT NULL,

   AGE            INT       NOT NULL,

   ADDRESS        CHAR(50),

   SALARY         REAL

);

Now insert a few 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 in 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