Skip site navigation (1) Skip section navigation (2)

Re: Noob question: how to auto-increment index field on INSERT?

From: APseudoUtopia <apseudoutopia(at)gmail(dot)com>
To: Ken MacDonald <drken567(at)gmail(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Noob question: how to auto-increment index field on INSERT?
Date: 2009-11-19 17:19:23
Message-ID: 27ade5280911190919h72410c37x6caaf62479b85de3@mail.gmail.com (view raw or flat)
Thread:
Lists: pgsql-novice
On Thu, Nov 19, 2009 at 11:55 AM, Ken MacDonald <drken567(at)gmail(dot)com> wrote:
> Hi,
> I have a PostgreSQL DB created by a Django model, with a field 'id' that is
> automatically created by Django as a primary key, type integer.
>
> I would like to create a new row by doing something like....
>
> INSERT INTO table (a, b, c, d) VALUES ('aa', 'bb', 'cc', 'dd')
>
> where I've been hoping that 'id' would get the next value of id available.
> Unfortunately, instead I get a 'duplicate primary key' error saying that
> 'id' is a duplicate, even though I'm not specifying it explicitly in the
> INSERT. What is the proper way to auto-increment a primary key?
> Thanks!
> Ken
>

CREATE TABLE "table" (
"id"  SERIAL PRIMARY KEY,  -- This is the auto-incrementing table, see
the "SERIAL" datatype in the docs
"data" TEXT NOT NULL
);


To insert, use the DEFAULT keyword.
INSERT INTO "table" ("id", "data") VALUES (DEFAULT, 'abc 123');

http://www.postgresql.org/docs/8.4/interactive/datatype-numeric.html#DATATYPE-SERIAL

In response to

Responses

pgsql-novice by date

Next:From: Ken MacDonaldDate: 2009-11-19 18:59:00
Subject: Re: Noob question: how to auto-increment index field on INSERT?
Previous:From: Thomas KellererDate: 2009-11-19 17:06:50
Subject: Re: Noob question: how to auto-increment index field on INSERT?

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group