-1

It looks to me that Postgresql deosn't support to add column before or after existing column, and it only adds the column as the last position. Often I need to add a column, but I don't want to add it at last, I have to drop the table and recreate the table, and insert the data that the table already has.

I would ask if there is an appoach to add a column at the desired position.

Tom
  • 5,848
  • 12
  • 44
  • 104

1 Answers1

2

Use the CREATE TABLE statement to create a new table with the specified column order and the new column.

CREATE TABLE new_table (
    id serial PRIMARY KEY,
    new_column datatype,
    old_column1 datatype,
    old_column2 datatype
);

Copy data from the old table to the new table using INSERT INTO

INSERT INTO new_table (id, new_column, old_column1, old_column2)
SELECT id, new_column, old_column1, old_column2 FROM old_table;

Give the new table the name of the old table, and rename the old table to a temporary name.

ALTER TABLE old_table RENAME TO old_table_temp;
ALTER TABLE new_table RENAME TO old_table;