Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL column type conversion from bigint to bigserial

When I try to change the data type of a column in a table by alter command...

alter table temp alter column id type bigserial; 

I get

ERROR:  type "bigserial" does not exist 

How can I change the datatype from bigint to bigserial?

like image 956
k s l kumar Avatar asked Aug 12 '15 12:08

k s l kumar


People also ask

How do you change Bigserial to bigint?

Basic commands to convert an existing bigint column with existing rows to a bigserial : CREATE SEQUENCE tbl_tbl_id_seq; ALTER TABLE tbl ALTER COLUMN tbl_id SET DEFAULT nextval('tbl_tbl_id_seq'); ALTER SEQUENCE tbl_tbl_id_seq OWNED BY tbl.

How do I change the datatype of 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 Postgres have bigint?

PostgreSQL allows a type of integer type namely BIGINT . It requires 8 bytes of storage size and can store integers in the range of -9, 223, 372, 036, 854, 775, 808 to +9, 223, 372, 036, 854, 775, 807.

What is int2 in PostgreSQL?

float4. single precision floating-point number. smallint. int2. signed two-byte integer.


1 Answers

As explained in the documentation, SERIAL is not a datatype, but a shortcut for a collection of other commands.

So while you can't change it simply by altering the type, you can achieve the same effect by running these other commands yourself:

CREATE SEQUENCE temp_id_seq; ALTER TABLE temp ALTER COLUMN id SET NOT NULL; ALTER TABLE temp ALTER COLUMN id SET DEFAULT nextval('temp_id_seq'); ALTER SEQUENCE temp_id_seq OWNED BY temp.id; 

Altering the owner will ensure that the sequence is removed if the table/column is dropped. It will also give you the expected behaviour in the pg_get_serial_sequence() function.

Sticking to the tablename_columnname_seq naming convention is necessary to convince some tools like pgAdmin to report this column type as BIGSERIAL. Note that psql and pg_dump will always show the underlying definition, even if the column was initially declared as a SERIAL type.

As of Postgres 10, you also have the option of using an SQL standard identity column, which handles all of this invisibly, and which you can easily add to an existing table:

ALTER TABLE temp ALTER COLUMN id   ADD GENERATED BY DEFAULT AS IDENTITY 
like image 126
Nick Barnes Avatar answered Sep 21 '22 13:09

Nick Barnes