Is it possible to reorder rows in SQL database? For example; how can I swap the order of 2nd row and 3rd row\'s values?
The order of the row is important to me since
I have a solution for this that I have used a few times. I keep an extra field "sort_order" in the table, and update this when reordering. I've used this in cases when I have some sort of containers with items, and the order of the items should be editable inside the container. When reordering, I only update the sort_order for the items in the current container, which means not to many (usually in practice only a few) rows have to be updated.
In short, I do the following:
[[id, sort_order], [id2, sort_order], ...]
update item set sort_order=SORT_ORDER where id=ID
(executemany) with merged list(If moving item to another container, after updating "container foreign key" move first or last depending on app.)
(If the update involves a large number of items, I do not think this solution is a good approach.)
I have made an example using python and mysql on http://wannapy.blogspot.com/2010/11/reorder-rows-in-sql-database.html (copy and try it) along with some extra explanations.
As others have stated use an order by.
Never depend on the order data exists in a physical table, always base it of the data you are working with, be it one or more key fields.
The order of the rows on the actual database should not matter.
You should use the ORDER BY clause in your queries to order them as you need.
In response to your post here, the answer you may be looking for is:
To order chronologically, add a DateAdded
or similar column with a datetime
or smalldatetime
datatype.
On all methods that insert into the database, make sure you insert CURRENT_TIMESTAMP
in the DateAdded
column.
On methods that query the database, add ORDER BY DateAdded
at the end of the query string.
NEVER rely on the physical position in the database system. It may work MOST of the time but definitely not ALL of the time.
First, let me agree with everyone here that the order in the table shouldn't matter. Use a separate [SortOrder] column that you update and include an Order By clause.
That said, SQL Server databases do allow for a single "clustered index" on a table that will actually force the position in the underlying table storage. Primarily useful if you have a big dataset and always query by something specific.
Databases can store the data in any way they want. Using the "order by" clause is the only way to guarantee an ordering of the data. In your bookmark example, you could have an integer field that indicates the ordering, and then update that field as a user moves things around. Then ORDER BY that column to get things in the right order.