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?
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.
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.
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.
float4. single precision floating-point number. smallint. int2. signed two-byte integer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With