Search code examples
mysqldatabasepostgresqlauto-increment

No auto Increment when MySql Database converted to Postgres database


In Mysql, ID is Auto Increment but when converted to Postgres there is no Auto Increment .

Mysql database

CREATE TABLE IF NOT EXISTS `cities` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `state_id` bigint(20) NOT NULL,
  `district_id` bigint(20) NOT NULL,
   `name` varchar(255) NOT NULL,
  `description` varchar(1000) DEFAULT NULL,
  `created_by` int(11) NOT NULL,
  `modified_by` int(11) DEFAULT NULL,
  `is_active` char(1) NOT NULL DEFAULT 'Y',
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `state_id` (`state_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

After Converted to postgres database

CREATE TABLE cities (
    "id" bigint NOT NULL,
    state_id bigint NOT NULL,
    district_id bigint NOT NULL,
    "name" varchar(255) NOT NULL,
    description varchar(1000),
    created_by int NOT NULL,
    modified_by int,
    is_active char(1) NOT NULL,
    created timestamp,
    modified timestamp,
    PRIMARY KEY ("id")
);

INSERT INTO cities(state_id, district_id, city_type, name, description,  
     created_by, modified_by, is_active, created, modified) 
VALUES 
    (1, 1, '', 'Ramtek', null, 1, null, 'Y',
     '2015-04-16 10:44:11', '2015-04-16 10:44:11');

Solution

  • You could use bigserial in such cases. It provides an auto increment feature in postgres:

    CREATE TABLE cities (
       "id" bigserial PRIMARY KEY,
    

    Not Null constraint is provided by default.

    Docs : http://www.postgresql.org/docs/current/static/datatype.html#DATATYPE-SERIAL