An alternative to using SERIAL or SMALLSERIAL columns in the table would be to create a sequence. For example both these tables below end up with identical data
create table t1
(
id SERIAL,
someData varchar
);
CREATE SEQUENCE t3_id_seq;
CREATE TABLE t3 (
id smallint NOT NULL DEFAULT nextval('t3_id_seq'),
someData varchar
);
ALTER SEQUENCE t3_id_seq OWNED BY t3.id;
insert into t1 (someData) values ('one');
insert into t1 (someData) values ('two');
insert into t1 (someData) values ('three');
insert into t3 (someData) values ('one');
insert into t3 (someData) values ('two');
insert into t3 (someData) values ('three');
The disadvantage of this method is that you would require a sequence of each table that had such an identity column (which is why I included the table name in the sequence name)
One advantage of using sequence over SERIAL could be that you can use the
LastVal()
function against the sequence to find out which was the last id inserted (if you wanted to update your GUI immediately)
But there is an even neater and more efficient way to do that (from version 8.2) using the
RETURNING
version of the insert statement (ref:
PostgreSQL: Documentation: 9.1: INSERT[
^])
E.g.
insert into t1 (someData) values ("four") RETURNING id