You can actually just reorder the columns, but I would hardly recommend it, and you have to be very careful if you decide to do this.
eg.
# CREATE TABLE test (a int, b int, c int);
# INSERT INTO test VALUES (1,2,3);
# SELECT * FROM test;
a | b | c
--- + --- + ---
1 | 2 | 3
(1 row)
Now for a complex bit, you need to connect to the database using the postgres user so that you can modify the system tables.
# SELECT relname, relfilenode FROM pg_class WHERE relname = 'test';
relname | relfilenode
--------- + -------------
test_t | 27666
(1 row)
# SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid = 27666;
attrelid | attname | attnum
---------- + ---------- + --------
27666 | tableoid | -7
27666 | cmax | -6
27666 | xmax | -5
27666 | cmin | -four
27666 | xmin | -3
27666 | ctid | -one
27666 | b | one
27666 | a | 2
27666 | c | 3
(9 rows)
attnum is a unique column, so you need to use a temporary value when you change the column numbers as such:
# UPDATE pg_attribute SET attnum = 4 WHERE attname = 'a' AND attrelid = 27666;
UPDATE 1
# UPDATE pg_attribute SET attnum = 1 WHERE attname = 'b' AND attrelid = 27666;
UPDATE 1
# UPDATE pg_attribute SET attnum = 2 WHERE attname = 'a' AND attrelid = 27666;
UPDATE 1
# SELECT * FROM test;
b | a | c
--- + --- + ---
1 | 2 | 3
(1 row)
Again, since this plays with database system tables, use extreme caution if you feel that you really need to do this.
This works with postgres 8.3 with previous versions, your movement may vary.
Russell Mar 18 '09 at 3:06 2009-03-18 03:06
source share