Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 'serial' to existing column in Postgres

Tags:

postgresql

I have a small table (~30 rows) in my Postgres 9.0 database with an integer ID field (the primary key) which currently contains unique sequential integers starting at 1, but which was not created using the 'serial' keyword.

How can I alter this table such that from now on inserts to this table will cause this field to behave as if it had been created with 'serial' as a type?

like image 983
nicolaskruchten Avatar asked Feb 28 '12 21:02

nicolaskruchten


People also ask

How do I add an identity column in PostgreSQL?

In PostgreSQL, the GENERATED AS IDENTITY constraint is used to create a PostgreSQL identity column. It allows users to automatically assign a unique value to a column. The GENERATED AS IDENTITY constraint is the SQL standard-conforming variant of the PostgreSQL's SERIAL column. Let's analyze the above syntax.

How do I alter a column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

Does PostgreSQL have auto increment?

PostgreSQL has the data types smallserial, serial and bigserial; these are not true types, but merely a notational convenience for creating unique identifier columns. These are similar to AUTO_INCREMENT property supported by some other databases.

What is the difference between serial and sequence in PostgreSQL?

There is essentially no difference.


2 Answers

Look at the following commands (especially the commented block).

DROP TABLE foo; DROP TABLE bar;  CREATE TABLE foo (a int, b text); CREATE TABLE bar (a serial, b text);  INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i; INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;  -- blocks of commands to turn foo into bar CREATE SEQUENCE foo_a_seq; ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); ALTER TABLE foo ALTER COLUMN a SET NOT NULL; ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later  SELECT MAX(a) FROM foo; SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result  INSERT INTO foo (b) VALUES('teste'); INSERT INTO bar (b) VALUES('teste');  SELECT * FROM foo; SELECT * FROM bar; 
like image 94
Euler Taveira Avatar answered Oct 22 '22 03:10

Euler Taveira


You can also use START WITH to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,

SELECT MAX(a) + 1 FROM foo; CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 
like image 32
John Powell Avatar answered Oct 22 '22 04:10

John Powell