211

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

ALTER TABLE person ALTER COLUMN dob POSITION 37;
2

12 Answers 12

197

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

16
  • 4
    'dump the database' :: great way to damage data. and hence "scrub the massive database" effect. Commented Nov 13, 2008 at 0:36
  • 57
    @Kent: Doubtful, the postgres devs go a long way to ensure data consistency and that would certainly apply to pg_dump. After all, what's the point of doing db backups if the restore is borked? Commented Nov 13, 2008 at 23:41
  • 1
    @Dana, yes, but you're adding 1) a big process to dump, and then you drop, and then you have a big time consuming load. If you have a seriously massive database, which is usually the case with 37 columns, you're going to have risks with disk IO choking. Commented Nov 14, 2008 at 6:22
  • @DanatheSane these are super old comments, but what Bill was saying is essentially the same thing, instead of doing a full database dump, you just dump the table (and dependencies), kill the original, then recreate. No need to take the whole database offline, or spend time re-creating something that's not affected. On the other hand, if there a lot of dependencies, I've found doing a full dump (as you suggested) to be much easier.
    – vol7ron
    Commented Mar 7, 2012 at 17:41
  • 1
    Here's why you might need column order - postgresql.org/docs/current/interactive/sql-copy.html - If a list of columns is specified, COPY will only copy the data in the specified columns to or from the file. If there are any columns in the table that are not in the column list, COPY FROM will insert the default values for those columns. Commented Jun 1, 2015 at 13:37
137

In PostgreSQL, while adding a field it would be added at the end of the table. If we need to insert into particular position then

    alter table tablename rename to oldtable;
    create table tablename (column defs go here); ### with all the constraints
    insert into tablename (col1, col2, col3) select col1, col2, col3 from oldtable;

WARNING: with this solution, other tables having foreign keys to tablename will keep referencing the oldtable, so you have any, you will have to fix them.

7
  • 7
    Wow this is great, I'm sure this should be the accepted answer! Commented Feb 28, 2019 at 22:51
  • 9
    You can also copy the current table to a new oldtable like this: CREATE TABLE oldtable AS SELECT * FROM tablename;
    – Ryan
    Commented Jul 24, 2020 at 23:09
  • 2
    Here's an example with real world values: insert into newTable (id, created, start, end, message) SELECT id, created, start, end, message FROM oldTable; Commented Sep 30, 2020 at 14:59
  • 12
    It is not that easy to move from one table to another as there are other objects related to them such us constraints.
    – thanos.a
    Commented Mar 19, 2021 at 8:27
  • 16
    I think this solution also messes up foreign keys. The ALTER TABLE ... RENAME TO ... seems to change existing foreign key relationships in other tables accordingly. That means that in the end foreign keys point to oldtable but the data is in the new table. I assume a manual migration of all foreign key relationships is required before one can properly drop oldtable.
    – bluenote10
    Commented Jun 23, 2021 at 7:49
39

One, albeit a clumsy option to rearrange the columns when the column order must absolutely be changed, and foreign keys are in use, is to first dump the entire database with data, then dump just the schema (pg_dump -s databasename > databasename_schema.sql). Next edit the schema file to rearrange the columns as you would like, then recreate the database from the schema, and finally restore the data into the newly created database.

3
  • 4
    Why a downvote? As the accepted answer points out, quoting the PostgreSQL Wiki: »The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.» This solution is not optimal (none of these answers are in the absence of a built-in operation to accomplish the task), but it does provide a way to rearrange the columns in a table.
    – Ville
    Commented Apr 27, 2016 at 15:19
  • 6
    I say again, there are no good ways to do this, and what I outline above is a valid way to rearrange columns if they absolutely must be rearranged. If you downvote my answer, please comment on why you feel it's an unacceptable solution.
    – Ville
    Commented Jun 22, 2017 at 6:32
  • 7
    In fact, this is a very good solution when the table is foreign key in another tables. All another solutions does not work in this escenario. Finally, use pg_dump --column-inserts -s databasename > databasename_schema.sql Commented Aug 11, 2017 at 15:45
30

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.

4
  • 2
    This seems like a pretty reasonable solution. It's too bad there aren't any GUI tools to automate this procedure. Commented Nov 28, 2014 at 0:10
  • 7
    good solution but only the data types are copied (no primary key, etc.)
    – Regisz
    Commented Dec 29, 2014 at 15:08
  • 1
    Alternatively - just use the view with the reordered columns as-is. There should be minimal performance degradation.
    – pscl
    Commented Feb 14, 2017 at 3:16
  • 1
    This is the best solution. Commented Jan 29, 2020 at 23:27
13

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.
0
7

Open the table in PGAdmin and in the SQL pane at the bottom copy the SQL Create Table statement. Then open the Query Tool and paste. If the table has data, change the table name to 'new_name', if not, delete the comment "--" in the Drop Table line. Edit the column sequence as required. Mind the missing/superfluous comma in the last column in case you have moved it. Execute the new SQL Create Table command. Refresh and ... voilà.

For empty tables in the design stage this method is quite practical.

In case the table has data, we need to rearrange the column sequence of the data as well. This is easy: use INSERT to import the old table into its new version with:

INSERT INTO new ( c2, c3, c1 ) SELECT * from old;

... where c2, c3, c1 are the columns c1, c2, c3 of the old table in their new positions. Please note that in this case you must use a 'new' name for the edited 'old' table, or you will lose your data. In case the column names are many, long and/or complex use the same method as above to copy the new table structure into a text editor, and create the new column list there before copying it into the INSERT statement.

After checking that all is well, DROP the old table and change the the 'new' name to 'old' using ALTER TABLE new RENAME TO old; and you are done.

2
  • 2
    Pretty sure this process is going to require re-creating all your FK constraints as well. Commented Mar 1, 2022 at 23:10
  • Before dropping the <old> table, you need to alter all the constraints and FKs, etc to point to the <new> table.
    – foobarna
    Commented Apr 24, 2023 at 8:30
4

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.

4

For those tempted to change column order like this, just know it won't work because whole table gets messed up. You'll receive an error like this: [XX000] ERROR: invalid memory alloc request size 18446744073709551613

Unfortunately, it seems like the attnum is not only used for retrieval of data but for storage as well.

The idea to drop whole table is all good and fine but you also have to drop all FKs, IXs and so on. I'll probably learn to live with my column being at back.

select *
from information_schema.columns
where table_name = 'table1';

update pg_catalog.pg_attribute
set attnum = 10 where attname = 'column_on_9_position_to_move_to_7';

update pg_catalog.pg_attribute
set attnum = 9 where attname = 'column_on_7_position_to_move_to_9';

update pg_catalog.pg_attribute
set attnum = 7 where attname = 'column_on_9_position_to_move_to_7';
1

I use Django and it requires id column in each table if you don't want to have a headache. Unfortunately, I was careless and my table bp.geo_location_vague didn't contain this field. I initialed little trick. Step 1:

CREATE VIEW bp.geo_location_vague_vw AS
    SELECT 
        a.id, -- I change order of id column here. 
        a.in_date,
        etc
    FROM bp.geo_location_vague a

Step 2: (without create table - table will create automaticaly!)

SELECT * into bp.geo_location_vague_cp2 FROM bp.geo_location_vague_vw

Step 3:

CREATE SEQUENCE bp.tbl_tbl_id_seq;
ALTER TABLE bp.geo_location_vague_cp2 ALTER COLUMN id SET DEFAULT nextval('tbl_tbl_id_seq');
ALTER SEQUENCE bp.tbl_tbl_id_seq OWNED BY bp.geo_location_vague_cp2.id;
SELECT setval('tbl_tbl_id_seq', COALESCE(max(id), 0)) FROM bp.geo_location_vague_cp2;

Because I need have bigserial pseudotype in the table. After SELECT * into pg will create bigint type insetad bigserial.

step 4: Now we can drop the view, drop source table and rename the new table in the old name. The trick was ended successfully.

1

I made a backup of my database's data structure in PLAIN format, and edited the column order in NotePad, then created a new database and ran all the code in a query. It worked 100%

1
  • 1
    plus 1 for using notepad for database administration tasks Commented May 7 at 7:30
1

In your migration file change the field order in the field array and the run migrate command will change the order of the columns. I tried like this and it worked for me.

0

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

1
  • you call it "workaround"?
    – Timeless
    Commented Nov 18, 2023 at 5:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.