Re: Am I using the SERIAL type properly?

Поиск
Список
Период
Сортировка
От Jeffrey Melloy
Тема Re: Am I using the SERIAL type properly?
Дата
Msg-id 4E677ABC-B418-11D7-B18E-000393C78AC0@visualdistortion.org
обсуждение исходный текст
Ответ на Am I using the SERIAL type properly?  ("Chad N. Tindel" <ctindel@falcon.csc.calpoly.edu>)
Список pgsql-general
> --------------------
> drop table A;
> create table A (
>     id SERIAL PRIMARY KEY,
>     foo int default 5,
>     bar int default 10
> );
>
> insert into A (id, foo, bar) values (1, 1, 1);
> insert into A (id, foo, bar) values (2, 2, 2);
> insert into A (id, foo, bar) values (3, 3, 3);
> insert into A (id, foo, bar) values (4, 4, 4);
   A serial data type will allow you to input values into it, but the
counter is still at 0.  That's why your first update statement's
nextval outputs "1".  It's not showing what was already inserted, it's
showing what would have been.  So at this point you need to set the
current value of id at 4.

> insert into A (foo, bar) values (5, 5);
> insert into A (foo, bar) values (6, 6);
> --------------------------
>
> The output that I get is:
>
> [ctindel@ct742301 Setup]$ p < a.sql
> DROP TABLE
> NOTICE:  CREATE TABLE will create implicit sequence 'a_id_seq' for
> SERIAL
> column 'a.id'
> NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index 'a_pkey'
> for table 'a'
> CREATE TABLE
> INSERT 44289 1
> INSERT 44290 1
> INSERT 44291 1
> INSERT 44292 1
> ERROR:  Cannot insert a duplicate key into unique index a_pkey
Here it's trying to insert "1"
> ERROR:  Cannot insert a duplicate key into unique index a_pkey
Here "2"

Nextval *sets* the sequence at N+1.

> INSERT 44319 1
>  id | foo | bar
> ----+-----+-----
>   1 |   1 |   1
> (1 row)
>
>  nextval
> ---------
>        1
   === These are unrelated.
>

Nextval is at 4 now, so the insert (foo,bar) works correctly.
>  id | foo | bar
> ----+-----+-----
>   1 |   1 |   1
>   2 |   2 |   2
>   3 |   3 |   3
>   4 |   4 |   4
>   5 |   5 |   5
> (5 rows)
>
>  nextval
> ---------
>        6
   < == This increases it again, showing the skipping behavior you were
seeing.


В списке pgsql-general по дате отправления:

Предыдущее
От: Martijn van Oosterhout
Дата:
Сообщение: Re: Am I using the SERIAL type properly?
Следующее
От: Harry Yau
Дата:
Сообщение: Which schema I am woking on??