tags:

views:

135

answers:

4

I saw this post but didn't understand if this was the same issue.

My database can be sorted on each column. Once the db is sorted, how do I maintain that order after my next query?

For example:
Order db by age:
sprintf(sql, "select * from Customer_Table ORDER BY age_ID LIMIT 100 OFFSET %s;", offset);

then the user looks at the next 100 customers

sprintf(sql, "select * from Customer_Table LIMIT 100 OFFSET %s;", offset); //next offset

The returned data is no longer ordered by age. How would I keep the last sort throughout the next query?

Do I have to pass in a variable to maintain state or does the database have some function for recalling it's last state?

+2  A: 

You have to specify the ORDER BY clause at each request.

The way this is optimized by your database system doesn't concern your client code.

jeje
+1  A: 

SQL databases do not guarantee any sorting, you have to specify it on each and every select call.

Otávio Décio
yes, I see that, looking if anyone had a creative way of maintaining the last sort.
Tommy
+2  A: 

Result sets generated by the Database engine are forgotten as soon as they're fulfilled. Everytime you query the database you have to provide your sort order.

CptSkippy
+2  A: 

Other than selecting the records into a temporary table, then selecting from that table, you would have to specify the ORDER BY in each query. The server does not retain any kind of state in regard to the previous query. Why is it a problem to re-specify the ORDER BY clause in subsequent queries?

Whether you use a temporary table or re-specify the entire query is a matter of how your application is structured.

Jack Straw
So the temporary table would always be filled with the last query maintaining that order. The next query would be on that temporary table, and the table would be replace with that query, etc. What are the methods for creating this table? It is not a problem but from a point of what a customer expects, it would be "stupid" to have to sort again. Extra clicks. Users want quality but it has to be fast or they leave your site.
Tommy
A temporary table will not guarentee an order. You would need to specify an ORDER BY when querying the temp table for the pieces. @Tommy: temp table creation varies by RDBMS, so would be specific to your platform.
Shannon Severance
ok thanks Shannon
Tommy
@Tommy: You write "it would be stupid to have to sort again". But this is what RDBMSs do. All you need to do in your program is remember the last sort order that the user requested, then build your SQL appropriately for the next query. This would not require more user input. It's up to you as the programmer to maintain the state. You mentioned "site" so I guess this is a website. There are many methods for maintaining state in a web app - session variables, hidden form fields, etc.
Jack Straw