tags:

views:

52

answers:

2

Hey!

I have a table that has 5 fields and has a total of 400 records. I added a new field which I called 'order' which, as the name suggests, is to keep an order in the records.

Since I added this after the records had been inserted I was wondering if there was a way to populate this field with the current order of the records using something like rownum via a sql query or do I need to use a PHP script to do the insert?

PS: I tried googling for rownum and didn't find anything useful :(

+1  A: 

ROWNUM is Oracle specific syntax. MySQL doesn't have a ranking function - the closest you can get is to use:

SELECT t.*, 
       @rownum := @rownum+1 'rownum'
  FROM TABLE t, (SELECT @rownum := 0) r

...but that will only number the rows - it won't reset when you cross a group, you'll have to query a group at a time.

OMG Ponies
+1  A: 

I don't think it is possible in SQL but you can use your primary key as initial order. After all, by default rows are sorted based on it anyway.

UPDATE table SET order = id;
vava
Good one :) Thanks
AntonioCS
Note that this solution works if and only if you never deleted any records from the table. rexem's answer will work and is a much more robust solution.
James McNellis
@James McNelis, no, it will work even if you delete something. Granted, order would not be continuous but it will be increasing nevertheless and that's what matters when you sort.
vava