Search code examples
postgresqlsequenceddlpostgresql-12

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

Solution

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