如何在Postgres中将现有的COLUMN类型更改为SERIAL?

时间:2020-01-18 09:58:50

标签: postgresql sequence ddl postgresql-12

以下语句无效:

ALTER TABLE my_table
ALTER COLUMN column_id set default nextval('my_table_column_id_seq');

那么如何将id列更改为自动递增?

错误:

null value in column \"column_id"\ violates non null constraint.

当我插入没有column_id时,就会发生这种情况。我需要它是自动递增。 Postgres版本是12。

我的插入内容:

INSERT INTO my_table (column2, column3)
VALUES ('rndmstring', 5);

2 个答案:

答案 0 :(得分:1)

您可以创建以column_id的现有值的最大值+1开头的序列:

CREATE SEQUENCE my_table_column_id_seq START WITH <MAX VALUE OF column_id+1>;

在检查此查询之后

SELECT 1
  FROM my_table
 HAVING COUNT(distinct column_id)=COUNT(column_id)
    AND SUM(CASE WHEN column_id IS NULL THEN 0 ELSE 1 END)=
        SUM(CASE WHEN column_id IS NULL THEN 1 ELSE 1 END);

针对相关列的值的非null和唯一性返回1,然后使用您现有的命令

ALTER TABLE my_table
ALTER COLUMN column_id SET DEFAULT nextval('my_table_column_id_seq');

命令并确保column_id的所有现有值都是唯一的,然后发出:

ALTER TABLE my_table ADD PRIMARY KEY(column_id);

Demo

答案 1 :(得分:0)

解决了这个问题。我在我的端点中将id设置为参数以创建新表。

因此而不是此nodejs端点:

exports.createMy_table = async (column_id, column2, column3) => {
  try {
    const result = await client.query(
      "INSERT INTO my_table (column_id, column2, column3) VALUES ($1, $2, $3
      [column_id, column2, column3]
    );
    return result.rows;
  } catch (err) {
    throw new Error(err);
  }
};

我创建的没有ID。

 exports.createMy_table = async (column2, column3) => {
      try {
        const result = await client.query(
          "INSERT INTO my_table (column2, column3) VALUES ($1, $2,
          [column2, column3]
        );
        return result.rows;
      } catch (err) {
        throw new Error(err);
      }
    };