tags:

views:

57

answers:

3

I have a table with a "SortID" column that is numbered using consecutive numbers. Whenever a row is deleted, it leaves a gap. Is there a way using pure SQL to update the rows with their row number? Something like this:

UPDATE tbl SET SortID={rowindex} ORDER BY SortID

(I realize this isn't valid SQL, that's why I'm asking for help)

This should set the first row to #1, the second row to #2... etc. Is this possible using SQL? Please forgive the poorly worded question, I'm not really sure the best way to ask this. :)

A: 

You can use mysql user defined variables

SET @pos=0;
SELECT @pos:=@pos+1, * FROM tbl ORDER BY SortID;
Dominik
+2  A: 

MySQL variables can be used for this.

SET @a:=0;
UPDATE tbl SET sortId=@a:=@a+1 ORDER BY sortId;
zombat
+1  A: 

Are you sure you need it? Presentation layer is used for numbering most of time.

Col. Shrapnel
This is for storing the sort order for a list of items that is maintained by the user.
Jon Tackabury
@Jon but whenever a row is deleted, this "gap" wouldn't affect a sort order
Col. Shrapnel
Not necessarily on deleting, but on inserts it does affect the order. I usually number the rows counting by 2's, then I can insert a new row in the middle and update the sortID in the same transaction.
Jon Tackabury