Is it possible to change the natural order of columns in Postgres?

后端 未结 8 1761
既然无缘
既然无缘 2020-12-05 13:25

Is it possible to change the natural order of columns in Postgres 8.1?

I know that you shouldn\'t rely on column order - it\'s not essential to what I am do

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 13:48

    I'm wanting the same. Yes, order isn't essential for my use-case, but it just rubs me the wrong way :)

    What I'm doing to resolve it is as follows.

    This method will ensure you KEEP any existing data,

    1. Create a new version of the table using the ordering I want, using a temporary name.
    2. Insert all data into that new table from the existing one.
    3. Drop the old table.
    4. Rename the new table to the "proper name" from "temporary name".
    5. Re-add any indexes you previously had.
    6. Reset ID sequence for primary key increments.

    Current table order:

    id, name, email
    

    1. Create a new version of the table using the ordering I want, using a temporary name.

    In this example, I want email to be before name.

    CREATE TABLE mytable_tmp
    (
      id SERIAL PRIMARY KEY,
      email text,
      name text
    );
    

    2. Insert all data into that new table from the existing one.

    INSERT INTO mytable_tmp   --- << new tmp table
    (
      id
    , email
    , name
    )
    SELECT
      id
    , email
    , name
    FROM mytable;  --- << this is the existing table
    

    3. Drop the old table.

    DROP TABLE mytable;
    

    4. Rename the new table to the "proper name" from "temporary name".

    ALTER TABLE mytable_tmp RENAME TO mytable;
    

    5. Re-add any indexes you previously had.

    CREATE INDEX ...
    

    6. Reset ID sequence for primary key increments.

    SELECT setval('public.mytable_id_seq', max(id)) FROM mytable;
    

提交回复
热议问题