Alter data type of a column to serial

后端 未结 3 1629
时光说笑
时光说笑 2020-12-13 17:59

In pgsql, is there a way to have a table of several values, and choose one of them (say, other_id), find out what its highest value is and make every new entry that is put i

3条回答
  •  無奈伤痛
    2020-12-13 18:35

    This happened because you may use serial data type only when you are creating new table or adding new column to a table. If you'll try to ALTER existing table using this data type you'll get an error. Because serial is not a true data type, but merely an abbreviation or alias for a bit longer query.

    In case you would like to reach the same effect, as you are expecting from using serial data type when you are altering existing table you may do this:

    CREATE SEQUENCE my_serial AS integer START 1 OWNED BY address.new_id;
    
    ALTER TABLE address ALTER COLUMN new_id SET DEFAULT nextval('my_serial');
    
    1. First line of query creates your own sequence with name my_serial. OWEND BY statement connects newly created sequence with exact column of your table. In your exact case table is address and column is new_id. START statement defines what value should this sequence start from.

    2. Second line alters your table with new default value, which will be determined by previously created sequence.

    It will brings you to the same result as you were expecting from using serial.

提交回复
热议问题