Create an auto incrementing primary key in postgresql, using a custom sequence:
Step 1, create your sequence:
create sequence splog_adfarm_seq
start 1
increment 1
NO MAXVALUE
CACHE 1;
ALTER TABLE fact_stock_data_detail_seq
OWNER TO pgadmin;
Step 2, create your table
CREATE TABLE splog_adfarm
(
splog_key INT unique not null,
splog_value VARCHAR(100) not null
);
Step 3, insert into your table
insert into splog_adfarm values (
nextval('splog_adfarm_seq'),
'Is your family tree a directed acyclic graph?'
);
insert into splog_adfarm values (
nextval('splog_adfarm_seq'),
'Will the smart cookies catch the crumb? Find out now!'
);
Step 4, observe the rows
el@defiant ~ $ psql -U pgadmin -d kurz_prod -c "select * from splog_adfarm"
splog_key | splog_value
----------+--------------------------------------------------------------------
1 | Is your family tree a directed acyclic graph?
2 | Will the smart cookies catch the crumb? Find out now!
(3 rows)
The two rows have keys that start at 1 and are incremented by 1, as defined by the sequence.
Bonus Elite ProTip:
Programmers hate typing, and typing out the nextval('splog_adfarm_seq')
is annoying. You can type DEFAULT
for that parameter instead, like this:
insert into splog_adfarm values (
DEFAULT,
'Sufficient intelligence to outwit a thimble.'
);
For the above to work, you have to define a default value for that key column on splog_adfarm table. Which is prettier.
IDENTITY
column instead of aserial
: stackoverflow.com/a/9875517/939860 – Erwin Brandstetter