Re: Reordering a table

From: Vibhor Kumar <vibhor(dot)kumar(at)enterprisedb(dot)com>
To: Howard Cole <howardnews(at)selestial(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Reordering a table
Date: 2011-02-22 17:18:14
Message-ID: 1036AD9E-260D-4E95-AEB9-BAE926E2DD00@enterprisedb.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Feb 22, 2011, at 10:10 PM, Howard Cole wrote:

> Hi,
>
> a puzzle to solve...
>
> I have a table with a primary key, and a timestamp, e.g.
>
> id stamp
> 1 2011-02-01 10:00
> 2 2011-02-01 09:00
> 3 2011-02-01 11:00
>
> Now for reasons too painful to go into, I need to reorder the id (sequence) so that they are in time order:
>
> id stamp
> 1 2011-02-01 09:00
> 2 2011-02-01 10:00
> 3 2011-02-01 11:00
>
> I thought I could do it by adding a third colum with the order in it, but I cannot think of a way to do this short of writing some code
>
> id stamp order
> 1 2011-02-01 10:00 2
> 2 2011-02-01 09:00 1
> 3 2011-02-01 11:00 3
>
> Any ideas?
>

If you are using PG 8.4 then you can try something with row_number as given below:
select id,stamp, row_number() over(order by stamp) from test;

Or

Create table test1 as select row_number() over(order by stamp) as id, stamp from test;

Thanks & Regards,
Vibhor Kumar

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Reid Thompson 2011-02-22 17:34:18 Re: work_mem = 900MB but Sort Method: external merge Disk: 304008kB
Previous Message Andreas Kretschmer 2011-02-22 17:17:40 Re: work_mem = 900MB but Sort Method: external merge Disk: 304008kB