I have this MySQL snippet:
CREATE TABLE seq_test (
id INT PRIMARY KEY AUTO_INCREMENT,
name TEXT
);
INSERT INTO seq_test(id, name) VALUES (1, 'one');
INSERT INTO seq_test(name) VALUES ('two');
When I try to write this to PostgreSQL:
CREATE TABLE seq_test (
id SERIAL PRIMARY KEY,
name TEXT
);
INSERT INTO seq_test(id, name) VALUES (1, 'one');
INSERT INTO seq_test(name) VALUES ('two');
I get the following error:
[23505] ERROR: duplicate key value violates unique constraint "seq_test_pkey"
Detail: Key (id)=(1) already exists.
This is because in PostgreSQL, inserting one does not increase the identifier for the next insert. How to create a table to match MySQL behavior?
This, of course, is an artificial example, but I am moving a large code base from MySQL to PostgreSQL, and parts of the code (which I do not control) use both styles (i.e. with and without ids), and they work in MySQL, but it does not work in PostgreSQL.
An ugly hack would always do SELECT setval('my_table_id_seq', (SELECT count(*) FROM my_table), TRUE)...
source
share