How to convert primary key from integer to serial?

别来无恙 提交于 2019-11-26 15:33:30
Erwin Brandstetter

serial is a pseudo data type, not an actual data type. It's an integer underneath with some additional DDL commands executed automatically:

  1. Create a sequence (with matching name by default).
  2. Set the column NOT NULL and the default to draw from that sequence.
  3. Make the column "own" the sequence.

Details:

A bigserial is the same, built around a bigint column. You want bigint, but you already achieved that. To transform an existing serial column into a bigserial (or smallserial), all you need to do is to ALTER the data type of the column. Sequences are generally based on bigint, so the same sequence can be used for any integer type.

To "change" a bigint into a bigserial or an integer into a serial, you just have to do the rest by hand:

The actual data type is still integer / bigint. Some clients like pgAdmin will display the data type serial in the reverse engineered CREATE TABLE script, if all criteria for a serial are met.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!