tags:

views:

1465

answers:

12

Hi,

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 need to display the value according to the order.

+9  A: 

Use ORDER BY in your SELECT query. For example, to order by a user's last name, use:

SELECT * FROM User ORDER BY LastName
John Millikin
+5  A: 

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.

Ben S
+2  A: 

I guess a simple order by would be what you're looking for?

select my_column from my_table order by my_order_column;
slipset
+1  A: 

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.

schooner
A: 

Thanks for all the answers. But 'Order by' won't work for me.

For example, I put a list of bookmarks in database. I want to display based on the result I get from query. (not in alphabet order). Just when they are inserted.

But user may re-arrange the position of the bookmark (in any way he/she wants). So I can't use 'order by'.

An example is how the bookmark display in the bookmark in firefox. User can switch position easily. How can I mention that in DB?

Thank you.

lucius
You're asking too much for one system to handle. You'll need a multi-step approach:(1) Add a my_order_column column to your table, like slipset suggests.(2) Always SELECT your data with "ORDER BY my_order_column".(3) Then provide a way for your users to change the value of my_order_column in your user interface.
eksortso
RDBMS's simply don't work that way, you need something to order it by, or you need to handle this kind of "arranging" in the UI, not through the DB.
Gus
A: 

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.

Graeme Perrow
+4  A: 

As others have mentioned, it's not a good idea to depend on the physical order of the database table. Relational tables are conceptually more like unordered sets than ordered lists. Assuming a certain physical order may lead to unpredictable results.

Sounds like what you need is a separate column that stores the user's preferred sort order. But you'll still need to do something in your query to display the results in that order.

It is possible to specify the physical order of records in a database by creating a clustered index, but that is not something you'd want to do on an arbitrary user-specified basis. And it may still lead to unexpected results.

John M Gant
A: 

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.

T Pops
+5  A: 

It sounds like you need another column like "ListOrder". So your table might look like:

BookMark ListOrder
======== =========
    d                1
    g                2
    b                3
    f                4
    a                5

Then you can "order by" ListOrder.

Select * from MyTable Order By ListOrder

If the user can only move a bookmark one place at a time, you can use integers as the ListOrder, and swap them. For example, if the user wants to move "f" up one row:

Update MyTable
    Set ListOrder=ListOrder+1
        Where ListOrder=(Select ListOrder-1 From MyTable where BookMark='f')

Update MyTable
    Set ListOrder=ListOrder-1
        Where BookMark='f'

If the user can move a bookmark up or down many rows at once, then you need to reorder a segment. For example, if the user wants to move "f" to the top of the list, you need to:

update MyTable
    Set ListOrder=ListOrder+1
        where ListOrder>=1 -- The New position
            and ListOrder <(Select ListOrder from MyTable where BookMark='f')

 update MyTable
     Set ListOrder=1 -- The New Position
         Where Bookmark='f'
Mike Lewis
Thank you for this idea. I guess I was trying to see if I can solve my problem without creating a new Coloumn.
lucius
But can this work if a bookmark is move more than 1 place at a time?For example, what if the user want to move "f" from 4 to 2?all g, b, a need to be updated.
lucius
Yes, That is my second example in the code above.
Mike Lewis
Thanks you Mike. I am not sure how to read your SQL example. What is the SQL statement and what are the values I need to fill in?update MyTable Set ListOrder=ListOrder+1 where ListOrder>=1 -- The New position and ListOrder <(Select ListOrder from MyTable where BookMark='f')update MyTable Set ListOrder=1 -- The New Position Where Bookmark='f'
lucius
Sorry, but this website didn't paste the code well.Two dashes -- indicate that the rest of the line is a commentUnfortunately pasting rearranged my lines.update MyTable Set ListOrder=ListOrder+1where ListOrder>=1and ListOrder <(Select ListOrder from MyTable where BookMark='f')update MyTable Set ListOrder=1Where Bookmark='f'
Mike Lewis
I formatted the SQL - is it still OK?
ChrisF
I tried it but it doesn't quite work:update test Set ordering=ordering+1 where ordering>=@newPosition and ordering <(Select ordering from test where id=@rowId) update test Set ordering=@newPosition Where id=@rowIdI ended up with two rows having the same order.
sabbour
A: 

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.

Bill
A: 

The question lacks any detail that would let anyone give you correct answer. Clearly you could read the records into memory and then update them. But this is bad on so many different levels.

The issue is like this. Depending on the schema that is actually implemented there is logic to the way that the records are physically written to disk. Sometimes they are written in order of insert and other times they are inserted with space between blocks (see extents).

So changing the physical order is not likely without swapping column data; and this has a deep effect on the various indices. You are left having to change the logical order.

As I read your update... I'm left to understand that you may have multiple users and each user is to have bookmarks that they want ordered. Looks like you need a second table that acts as an intersection between the user and the bookmark. Then all you need is an inner join and an order by.

But there is not enough information to offer a complete solution.

Richard
A: 

Add a position column to your table and store as a simple integer.

If you need to support multiple users or lists, your best bet is to create a bookmarks table, an users table and a table to link them.

  • bookmarks: id,url
  • users: id,name
  • users_bookmarks: user_id, bookmark_id, position, date_created

Assuming date_created is populated when inserting rows you can get secondary list ordering based on date.

select bookmark_id from users_bookmarks where user_id = 1 order by position, date_created;
garrow