How do I alter the position of a column in a PostgreSQL database table?

前端 未结 9 1525
[愿得一人]
[愿得一人] 2020-11-30 00:25

I\'ve tried the following, but I was unsuccessful:

ALTER TABLE person ALTER COLUMN dob POSITION 37;
相关标签:
9条回答
  • 2020-11-30 00:53

    There are some workarounds to make it possible:

    1. Recreating the whole table

    2. Create new columns within the current table

    3. Create a view

    https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html

    0 讨论(0)
  • 2020-11-30 00:56

    I was working on re-ordering a lot of tables and didn't want to have to write the same queries over and over so I made a script to do it all for me. Essentially, it:

    1. Gets the table creation SQL from pg_dump
    2. Gets all available columns from the dump
    3. Puts the columns in the desired order
    4. Modifies the original pg_dump query to create a re-ordered table with data
    5. Drops old table
    6. Renames new table to match old table

    It can be used by running the following simple command:

    ./reorder.py -n schema -d database table \
        first_col second_col ... penultimate_col ultimate_col --migrate
    

    It prints out the sql so you can verify and test it, that was a big reason I based it on pg_dump. You can find the github repo here.

    0 讨论(0)
  • 2020-11-30 01:00

    This post is old and probably solved but I had the same issue. I resolved it by creating a view of the original table specifying the new column order.

    From here I could either use the view or create a new table from the view.

        CREATE VIEW original_tab_vw AS
        SELECT a.col1, a.col3, a.col4, a.col2
        FROM original_tab a
        WHERE a.col1 IS NOT NULL --or whatever
    
        SELECT * INTO new_table FROM original_tab_vw
    

    Rename or drop the original table and set the name of the new table to the old table.

    0 讨论(0)
提交回复
热议问题