简体   繁体   中英

PostgreSQL: change order of columns in query

I have a huge query with about 30 columns. I ordered the query with:

Select *
From
.
.
.
order by id,status

Now I want that in the result to present columns in certain way. The id column will be first, followed by status column and then all the rest.

is there a way to do that ( without manually specifying 30 column names in select). Something like: Select id,status, REST

this will give you all columns except those you don't want to

SELECT id, status,' || array_to_string(ARRAY(SELECT 'o' || '.' || c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'table_name' 
            AND  c.column_name NOT IN('id', 'status')
    ), ',') || ' FROM officepark As o' As sqlstmt

The "select *" will return the fields in the order in which they were listed when the table was created. If you want them returned in a particular order, just be sure to create the table with that order.

If you have to do it repeatly, you could create a new table:

CREATE TABLE FOO as
SELECT id, status, mydesiredorder

Or just a view,don't forget to move index constraint and foreign keys. If you must do it just once, was faster specify 30 columns than ask here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM