231

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

ALTER TABLE person ALTER COLUMN dob POSITION 37;
1
  • 7
    This question was answered before Commented Nov 13, 2008 at 8:55

13 Answers 13

215

"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.

You can also 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.

That's pretty weak, but this is not a knock against PostgreSQL. In their defense, standard SQL has no solution for repositioning a column, and some other SQL implementations besides PostgreSQL follow this standard.

SQL implementations that support changing the ordinal position of a column are defining an non-standard extension to SQL syntax.

Sign up to request clarification or add additional context in comments.

15 Comments

'dump the database' :: great way to damage data. and hence "scrub the massive database" effect.
@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?
@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.
@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.
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.
|
149

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.

6 Comments

You can also copy the current table to a new oldtable like this: CREATE TABLE oldtable AS SELECT * FROM tablename;
Here's an example with real world values: insert into newTable (id, created, start, end, message) SELECT id, created, start, end, message FROM oldTable;
It is not that easy to move from one table to another as there are other objects related to them such us constraints.
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 yup, realized today I broke all my foreign keys on my app and now, nothing's working anymore... answer should definitely have a warning about that
|
47

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.

1 Comment

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
32

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.

3 Comments

good solution but only the data types are copied (no primary key, etc.)
Alternatively - just use the view with the reordered columns as-is. There should be minimal performance degradation.
Downvote for suggesting creating a view as a "solution" to the problem. The point of putting columns in the order they're most pertinent is to make maintaining the database easier, not harder.
15

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.

Comments

9

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 Comments

Pretty sure this process is going to require re-creating all your FK constraints as well.
Before dropping the <old> table, you need to alter all the constraints and FKs, etc to point to the <new> table.
6

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.

Comments

6

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

2 Comments

Can you please explain more? Do you just set the attnum and that's all?
Nope, it would seem you could do that, but in reality, this table defines how data are stored on disk and when you update attnum then data reader fails with incorrect data conversions and so on.
2

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.

Comments

2

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%

Comments

2

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.

Comments

0

I make heavy use the Comment field in PostgreSQL. Most IDE's allow you to order by the Comment field in addition to the usual fields (e.g. Column Name, Data Type, etc.).

I usually prefix the column Comment with some sort of number scheme, then order by the Comment field within my IDE; for example, 01 USERNAME, 02 USER EMAIL ADDRESS.

This allows me to add another column to the table months or years later, then just modify the prefix in the Comment fields to have the IDE present the columns in the order I want them to display for me and other developers.

Comments

0

I suggest altogether avoiding the issue - i.e. the fact that your 'useful' columns are often added later and are therefore located at the end of the DDL definition - by using DataGrip systematically. Jetbrains DataGrip is free since December 2025 and it is by far the best SQL tool, vastly superior to PgAdmin and many other (free and other) tools. It has a learning curve, but for anyone working in SQL more than a few hours a week, it's absolutely worth doing.

In Datagrip you can rearrange the column sequence as you please. While working on (a set of) table(s) you simply keep them open in a separate window. I typically have 10 or so at hand. Until they are closed, the ad-hoc column order remains unchanged. Depending on the problem you're working on, that order can change.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.