Re: serial - Mailing list pgsql-general

From Scott Marlowe
Subject Re: serial
Date
Msg-id dcc563d10812040606u7fef5049u6d4cd7754175449@mail.gmail.com
Whole thread Raw
In response to serial  (Gustavo Rosso <grosso@sadaic.org.ar>)
Responses Re: serial
List pgsql-general
On Thu, Dec 4, 2008 at 7:42 AM, Gustavo Rosso <grosso@sadaic.org.ar> wrote:
> I created this table:
>
> create table se (n  serial);
>
> Column |  Type      |                   Modifiers
> ---------+---------+------------------------------------------------
> n           | integer    | not null default nextval('se_n_seq'::regclass)
>
> I inserted two record, later select, but column n (serial) no
> auto-incremented
> banco=# select * from se;
> n
> ---
> 0
> 0
> (2 rows)
>
> Why?

Because MySQL taught you bad habits?  You told the db to insert a 0,
so it inserted a 0.  If you told it to insert a NULL, it would proceed
to do that too.  There are several ways to have it use the serial /
sequence properly...  You can use the default keyword, or leave out
the field altogether (assuming you have > 1 field I guess), or you can
insert from the sequence yourself:

smarlowe=# create table test (i serial primary key, t text);
NOTICE:  CREATE TABLE will create implicit sequence "test_i_seq" for
serial column "test.i"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index
"test_pkey" for table "test"
CREATE TABLE
smarlowe=# insert into test (t) values ('this is text');
INSERT 0 1
smarlowe=# insert into test (i,t) values (DEFAULT,'this is more text');
INSERT 0 1
smarlowe=# insert into test (i,t) values (nextval('test_i_seq'),'even
more text');
INSERT 0 1
smarlowe=# select nextval('test_i_seq');
 nextval
---------
       4
(1 row)

smarlowe=# insert into test (i,t) values (4,'last bit of text');
INSERT 0 1
smarlowe=# select * from test;
 i |         t
---+-------------------
 1 | this is text
 2 | this is more text
 3 | even more text
 4 | last bit of text
(4 rows)

Hope that helps.

pgsql-general by date:

Previous
From: "Pavel Stehule"
Date:
Subject: Re: serial
Next
From: "Scott Marlowe"
Date:
Subject: Re: serial