Auto incrementing primary key in postgresql:
Create your table:
CREATE TABLE epictable
(
mytable_key serial primary key,
moobars VARCHAR(40) not null,
foobars DATE
);
Insert values into your table:
insert into epictable(moobars,foobars) values('delicious moobar','2012-05-01');
insert into epictable(moobars,foobars) values('WorldWideBlag','2012-05-02');
select * from your table:
select * from epictable
mytable_key | moobars | foobars
-------------+-----------------------+------------
1 | delicious moobar | 2012-05-01
2 | WorldWideBlag | 2012-05-02
(2 rows)
Observe that mytable_key column has been auto incremented.
Postgresql COPY doesn't observe serials
An auto incrementing serial key doesn't assert itself with bulk imports of data from file, like COPY
command does. You'll get a
psql:ERROR: duplicate key value violates unique constraint
. One way to fix that is copy it into a new table then use insert thustly:
COPY epictable TO '/tmp/etbackup.csv' DELIMITER ',' CSV HEADER;
CREATE TABLE epictable2 ( mytable_key integer,
moobars VARCHAR(40) not null,
foobars DATE );
COPY epictable2(mytable_key, moobars, foobars) FROM
'/tmp/etbackup.csv' DELIMITER ',' CSV HEADER;
--and again to make the duplicates requiring an autoincrement:
COPY epictable2(mytable_key, moobars, foobars) FROM
'/tmp/etbackup.csv' DELIMITER ',' CSV HEADER;
insert into epictable(moobars, foobars) (
select moobars, foobars from epictable2
);
select * from epictable;
┌─────────────┬──────────────────┬────────────┐
│ mytable_key │ moobars │ foobars │
├─────────────┼──────────────────┼────────────┤
│ 1 │ delicious moobar │ 2012-05-01 │
│ 2 │ WorldWideBlag │ 2012-05-02 │
│ 3 │ delicious moobar │ 2012-05-01 │
│ 4 │ WorldWideBlag │ 2012-05-02 │
│ 5 │ delicious moobar │ 2012-05-01 │
│ 6 │ WorldWideBlag │ 2012-05-02 │
└─────────────┴──────────────────┴────────────┘
Observe Auto-incrementing happens on mytable_key
with COPY
.
ProTips:
You should always be using a primary key on your table because postgresql internally uses hash table structures to increase the speed of inserts, deletes, updates and selects. If a primary key column (which is forced unique and non-null) is available, it can be depended on to provide a unique seed for the hash function. If no primary key column is available, the hash function becomes inefficient as it selects some other set of columns as a key.
If you want more control over the behavior of the serial key, then see postgresql sequences.
IDENTITY
column instead of aserial
: stackoverflow.com/a/9875517/939860