Sampo Kaarenmaa
Sampo Kaarenmaa

Reputation: 137

How to change existing COLUMN type to SERIAL in postgres?

The following statement doesn't work:

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

So how to change id column to auto increment?

Error:

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

This happens when I insert without column_id. I need it to be auto increment. Postgres Version is 12.

My insert:

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

Upvotes: 1

Views: 3300

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65105

You can create the sequence starting with the max value +1 of existing values for column_id :

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

after checking out if this query

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);

returns 1 for non-null and uniqueness of the concerned column's values, and then use your existing command

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

command and make sure all the existing values for column_id is unique, then issue :

ALTER TABLE my_table ADD PRIMARY KEY(column_id);

Demo

Upvotes: 2

Sampo Kaarenmaa
Sampo Kaarenmaa

Reputation: 137

Solved this. I had the id set as parameter in my endpoint for creating a new table.

So instead of this nodejs endpoint:

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);
  }
};

I create without 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);
      }
    };

Upvotes: 0

Related Questions